Skip to content
Newer
Older
100644 44 lines (32 sloc) 1.33 KB
332dab1 @kschiess . A really small erb parser.
authored Jan 21, 2011
1 $:.unshift File.dirname(__FILE__) + "/../lib"
2 require 'parslet'
3
4 class ErbParser < Parslet::Parser
205c2ec @floere + erb example: transform
floere authored Jan 21, 2011
5 rule(:ruby) { (str('%>').absnt? >> any).repeat.as(:ruby) }
4b8673f @floere Added comment erb tag.
floere authored Jan 21, 2011
6
205c2ec @floere + erb example: transform
floere authored Jan 21, 2011
7 rule(:expression) { (str('=') >> ruby).as(:expression) }
8 rule(:comment) { (str('#') >> ruby).as(:comment) }
9 rule(:code) { ruby.as(:code) }
4b8673f @floere Added comment erb tag.
floere authored Jan 21, 2011
10 rule(:erb) { expression | comment | code }
11
12 rule(:erb_with_tags) { str('<%') >> erb >> str('%>') }
ad813dc @floere A slightly bigger erb parser, including expressions.
floere authored Jan 21, 2011
13 rule(:text) { (str('<%').absnt? >> any).repeat(1) }
4b8673f @floere Added comment erb tag.
floere authored Jan 21, 2011
14
205c2ec @floere + erb example: transform
floere authored Jan 21, 2011
15 rule(:text_with_ruby) { (text.as(:text) | erb_with_tags).repeat.as(:text) }
ad813dc @floere A slightly bigger erb parser, including expressions.
floere authored Jan 21, 2011
16 root(:text_with_ruby)
332dab1 @kschiess . A really small erb parser.
authored Jan 21, 2011
17 end
18
205c2ec @floere + erb example: transform
floere authored Jan 21, 2011
19 parser = ErbParser.new
20 p parser.parse "The value of x is <%= x %>."
21 p parser.parse "<% 1 + 2 %>"
22 p parser.parse "<%# commented %>"
23
24
25 evaluator = Parslet::Transform.new do
26
27 erb_binding = binding
28
29 rule(:code => { :ruby => simple(:ruby) }) { eval(ruby, erb_binding); '' }
30 rule(:expression => { :ruby => simple(:ruby) }) { eval(ruby, erb_binding) }
31 rule(:comment => { :ruby => simple(:ruby) }) { '' }
32
33 rule(:text => simple(:text)) { text }
34 rule(:text => sequence(:texts)) { texts.join }
35
36 end
37
38 puts evaluator.apply(parser.parse(<<-ERB
39 The <% a = 2 %>not printed result of "a = 2".
40 The <%# a = 1 %>not printed non-evaluated comment "a = 1", see the value of a below.
41 The <%= 'nicely' %> printed result.
42 The <% b = 3 %>value of a is <%= a %>, and b is <%= b %>.
43 ERB
44 ))
Something went wrong with that request. Please try again.