Class: Curly::Compiler

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

Overview

Compiles Curly templates into executable Ruby code.

A template must be accompanied by a presenter class. This class defines the components that are valid within the template.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(presenter_class) ⇒ Compiler



54
55
56
57
# File 'lib/curly/compiler.rb', line 54

def initialize(presenter_class)
  @presenter_classes = [presenter_class]
  @parts = []
end

Class Method Details

.compile(template, presenter_class) ⇒ Object

Compiles a Curly template to Ruby code.

template - The template String that should be compiled. presenter_class - The presenter Class.

Raises InvalidComponent if the template contains a component that is not allowed. Raises IncorrectEndingError if a conditional block is not ended in the correct order - the most recent block must be ended first. Raises IncompleteBlockError if a block is not completed. Returns a String containing the Ruby code.



26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/curly/compiler.rb', line 26

def self.compile(template, presenter_class)
  if presenter_class.nil?
    raise ArgumentError, "presenter class cannot be nil"
  end

  tokens = Scanner.scan(template)
  nodes = Parser.parse(tokens)

  compiler = new(presenter_class)
  compiler.compile(nodes)
  compiler.code
end

.valid?(template, presenter_class) ⇒ Boolean

Whether the Curly template is valid. This includes whether all components are available on the presenter class.

template - The template String that should be validated. presenter_class - The presenter Class.

Returns true if the template is valid, false otherwise.



46
47
48
49
50
51
52
# File 'lib/curly/compiler.rb', line 46

def self.valid?(template, presenter_class)
  compile(template, presenter_class)

  true
rescue Error
  false
end

Instance Method Details

#codeObject



65
66
67
68
69
70
71
72
73
74
# File 'lib/curly/compiler.rb', line 65

def code
  "buffer = ActiveSupport::SafeBuffer.new\nbuffers = []\npresenters = []\noptions_stack = []\n\#{@parts.join(\"\\n\")}\nbuffer\n"
end

#compile(nodes) ⇒ Object



59
60
61
62
63
# File 'lib/curly/compiler.rb', line 59

def compile(nodes)
  nodes.each do |node|
    send("compile_#{node.type}", node)
  end
end