Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

+ erb example: transform

  • Loading branch information...
commit 205c2ecc7a55defc5a921c295e253f0f8dc2e1c6 1 parent 4b8673f
Florian R. Hanke floere authored committed
Showing with 31 additions and 7 deletions.
  1. +31 −7 example/erb.rb
38 example/erb.rb
View
@@ -2,19 +2,43 @@
require 'parslet'
class ErbParser < Parslet::Parser
- rule(:code) { (str('%>').absnt? >> any).repeat.as(:code) }
+ rule(:ruby) { (str('%>').absnt? >> any).repeat.as(:ruby) }
- rule(:expression) { (str('=') >> code).as(:expression) }
- rule(:comment) { (str('#') >> code).as(:comment) }
+ rule(:expression) { (str('=') >> ruby).as(:expression) }
+ rule(:comment) { (str('#') >> ruby).as(:comment) }
+ rule(:code) { ruby.as(:code) }
rule(:erb) { expression | comment | code }
rule(:erb_with_tags) { str('<%') >> erb >> str('%>') }
rule(:text) { (str('<%').absnt? >> any).repeat(1) }
- rule(:text_with_ruby) { (text.as(:text) | erb_with_tags).repeat }
+ rule(:text_with_ruby) { (text.as(:text) | erb_with_tags).repeat.as(:text) }
root(:text_with_ruby)
end
-p ErbParser.new.parse "The value of x is <%= x %>."
-p ErbParser.new.parse "<% 1 + 2 %>"
-p ErbParser.new.parse "<%# commented %>"
+parser = ErbParser.new
+p parser.parse "The value of x is <%= x %>."
+p parser.parse "<% 1 + 2 %>"
+p parser.parse "<%# commented %>"
+
+
+evaluator = Parslet::Transform.new do
+
+ erb_binding = binding
+
+ rule(:code => { :ruby => simple(:ruby) }) { eval(ruby, erb_binding); '' }
+ rule(:expression => { :ruby => simple(:ruby) }) { eval(ruby, erb_binding) }
+ rule(:comment => { :ruby => simple(:ruby) }) { '' }
+
+ rule(:text => simple(:text)) { text }
+ rule(:text => sequence(:texts)) { texts.join }
+
+end
+
+puts evaluator.apply(parser.parse(<<-ERB
+The <% a = 2 %>not printed result of "a = 2".
+The <%# a = 1 %>not printed non-evaluated comment "a = 1", see the value of a below.
+The <%= 'nicely' %> printed result.
+The <% b = 3 %>value of a is <%= a %>, and b is <%= b %>.
+ERB
+))
Please sign in to comment.
Something went wrong with that request. Please try again.