Sha256: 7d217c725d66ed884dcc8cc01e6347a2215bd060bb70308e640fc0c08b8a46a5

Contents?: true

Size: 1.33 KB

Versions: 11

Compression:

Stored size: 1.33 KB

Contents

# Please also look at the more naive 'erb.rb'. This shows how to optimize an
# ERB like parser using parslet. 

$:.unshift File.join(File.dirname(__FILE__), "/../lib")

require 'parslet'
require './qed/applique/gobbleup'
require 'parslet/accelerator'

class ErbParser < Parslet::Parser
  rule(:ruby) { (str('%>').absent? >> any).repeat.as(:ruby) }
  
  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('<%').absent? >> any).repeat(1) }
  
  rule(:text_with_ruby) { (text.as(:text) | erb_with_tags).repeat.as(:text) }
  root(:text_with_ruby)
end

parser = ErbParser.new

A = Parslet::Accelerator
optimized = A.apply(parser, 
  A.rule((A.str(:x).absent? >> A.any).repeat(1)) { GobbleUp.new(x, 1) }, 
  A.rule((A.str(:x).absent? >> A.any).repeat(0)) { GobbleUp.new(x, 0) })

input = File.read(File.dirname(__FILE__) + "/big.erb")

# Remove the comment marks here to see what difference the optimisation makes.
# Commented out for the acceptance tests to run. 
#
# require 'benchmark'
# Benchmark.bm(7) do |bm|
#   bm.report('original') { parser.parse(input) }
#   bm.report('gobble') { optimized.parse(input) }
# end
p optimized.parse(input)

Version data entries

11 entries across 11 versions & 2 rubygems

Version Path
parslet-2.0.0 example/optimized_erb.rb
parslet-1.8.2 example/optimized_erb.rb
parslet-1.8.1 example/optimized_erb.rb
parslet-1.8.0 example/optimized_erb.rb
swift-pyrite-0.1.1 vendor/bundle/ruby/2.0.0/gems/parslet-1.7.1/example/optimized_erb.rb
swift-pyrite-0.1.0 vendor/bundle/ruby/2.0.0/gems/parslet-1.7.1/example/optimized_erb.rb
parslet-1.7.1 example/optimized_erb.rb
parslet-1.7.0 example/optimized_erb.rb
parslet-1.6.2 example/optimized_erb.rb
parslet-1.6.1 example/optimized_erb.rb
parslet-1.6.0 example/optimized_erb.rb