Class: Ejs::Compiler

Inherits:
Object
  • Object
show all
Defined in:
lib/ejs/compiler.rb

Instance Method Summary collapse

Constructor Details

#initializeCompiler

Returns a new instance of Compiler.



8
9
10
# File 'lib/ejs/compiler.rb', line 8

def initialize
  @parser = Parser.new
end

Instance Method Details

#compile(source_path, namespace = nil, target_path = source_path.gsub(/\.ejs\Z/, '.js')) ⇒ Object



12
13
14
15
16
17
# File 'lib/ejs/compiler.rb', line 12

def compile(source_path, namespace = nil, target_path = source_path.gsub(/\.ejs\Z/, '.js'))
  File.open(target_path, 'w') do |target_file|
    target_file.write(AUTOGENERATED+"\n\n")
    target_file.write(js_source(source_path, namespace))
  end
end

#js_source(source_path, namespace = nil, output_as_array = false) ⇒ Object

compile a ejs file into javascript



20
21
22
23
24
25
# File 'lib/ejs/compiler.rb', line 20

def js_source(source_path, namespace = nil, output_as_array = false)
  template_name = File.basename(source_path, ".ejs")
  template_name = "#{namespace}.#{template_name}" if namespace
  
  js_source_from_string(template_name, File.read(source_path), output_as_array)
end

#js_source_from_string(template_name, content, output_as_array = false) ⇒ Object

compile a string containing ejs source into javascript



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/ejs/compiler.rb', line 28

def js_source_from_string(template_name, content, output_as_array = false)
  buffer = []
  parsed = @parser.parse(content)
  if parsed.nil?
    raise ParseError.new(@parser.failure_reason, @parser.failure_line, @parser.failure_column)
  end
  
  template_namespace(buffer, template_name)
  template_header(buffer, template_name)
  parsed.elements.each do |element|
    push_content(buffer, element)
  end
  template_footer(buffer)
        
  output_as_array ? buffer : buffer.join("\n")
end