Skip to content

Instantly share code, notes, and snippets.

@Wardrop
Last active August 29, 2015 14:13
Show Gist options
  • Save Wardrop/604f5ec38315e510ecff to your computer and use it in GitHub Desktop.
Save Wardrop/604f5ec38315e510ecff to your computer and use it in GitHub Desktop.
Transform value while preserving key example
require 'parslet'
class ExampleParser < Parslet::Parser
root(:root)
rule(:root) { width >> str("x") >> height }
rule(:width) { match["0-9"].repeat(1).as(:width) }
rule(:height) { match["0-9"].repeat(1).as(:height) }
end
class ExampleTransform < Parslet::Transform
rule(:width => simple(:w)) { Integer(w) }
rule(:height => simple(:h)) { Integer(h) }
# rule(:width => simple(:w), :height => simple(:h)) { {width: Integer(w), height: Integer(h) } }
end
p tree = ExampleParser.new.parse('400x600')
p ExampleTransform.new.apply(tree)
#=> {:width=>400, :height=>600}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment