Sha256: 5bfac60c0568daa8fa3d48b3442796c343cb41b963d10165abe31037a64ddc3f

Contents?: true

Size: 1.37 KB

Versions: 4

Compression:

Stored size: 1.37 KB

Contents

require "antelope/template/errors"
require "antelope/template/scanner"
require "antelope/template/compiler"


module Antelope
  class Template

    NO_SOURCE = Object.new


    def initialize(input, source = NO_SOURCE)
      @input  = normalize_input(input)
      @source = determine_source(input, source)
    end

    def parse
      @result ||= begin
        scanner  = Scanner.new(@input, @source)
        compiler = Compiler.new(scanner.scan)
        compiler.compile
      end
    end

    def result(binding = TOPLEVEL_BINDING.dup)
      eval(parse, binding, fake_name, 0)
    end

    alias_method :run, :result
    alias_method :call, :result

    private

    def normalize_input(input)
      case
      when String === input
        input
      when input.respond_to?(:read)
        input.read
      when input.respond_to?(:open)
        input.open("r") { |f| f.read }
      else
        raise ArgumentError, "Received #{input.class}, expected " \
          "#{String}, #read"
      end
    end

    def determine_source(input, source)
      case
      when source != NO_SOURCE
        source
      when input.respond_to?(:to_path)
        input.to_path
      else
        "(template)"
      end
    end

    def fake_name
      File.join(File.dirname(@source),
        "_#{File.basename(@source, '.*')}.rb")
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
antelope-0.3.2 lib/antelope/template.rb
antelope-0.3.0 lib/antelope/template.rb
antelope-0.2.4 lib/antelope/template.rb
antelope-0.2.3 lib/antelope/template.rb