Skip to content

Instantly share code, notes, and snippets.

@tristanoneil
Created June 23, 2014 15:53
Show Gist options
  • Save tristanoneil/3bb349e7f458afc6e08c to your computer and use it in GitHub Desktop.
Save tristanoneil/3bb349e7f458afc6e08c to your computer and use it in GitHub Desktop.
require 'parslet'
recipe = <<EOH
:1 oz: @1 :60 Minutes:
:1 oz: @2 :30 Minutes:
EOH
class BierDown < Parslet::Parser
rule(:colon) { match(':') }
rule(:at) { match('@') }
rule(:number) { match('[0-9]').repeat(1) }
rule(:word) { match('[a-zA-Z]').repeat(1) }
rule(:space) { match('\s') }
rule(:space?) { space.maybe }
rule(:text) { (colon.absent? >> at.absent? >> any).repeat(1) }
rule(:modifier) { colon >> number.as(:amount) >> space? >> word.as(:unit) >> colon }
rule(:reference) { str('@') >> number.as(:id) }
rule(:line) { (text | modifier | reference).repeat }
root(:line)
end
tree = BierDown.new.parse(recipe)
tree.each do |item|
puts "#{item[:amount]} #{item[:unit]}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment