Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#!/usr/bin/env ruby
require 'parslet'
class MyParser < Parslet::Parser
rule(:sentence) { (greeting >> space >> name >> exclamation.maybe).as(:result) }
rule(:greeting) { (str('Hello') | str('Goodbye')).as(:greeting) }
rule(:name) { match(/[A-Za-z]/).repeat(1).as(:name) }
rule(:space) { match(/\s/).repeat(1) }
rule(:exclamation) { str('!') }
root(:sentence)
end
class Transformer < Parslet::Transform
rule(name: simple(:n), greeting: simple(:g)) do
{ name: n.to_s, presence: (g == 'Hello' ? true : false) }
end
end
class Person
def initialize(name, here)
@name = name
@here = here
end
attr_accessor :name, :here
def present?
here
end
end
raw = MyParser.new.parse("Hello Laura!")
transformed = Transformer.new.apply(raw)[:result]
person = Person.new(transformed[:name], transformed[:presence])
if person.present?
puts person.name + ' is here'
else
puts person.name + ' is not here'
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment