Last active
December 21, 2016 03:04
-
-
Save epitron/6736aba790ab6d2fdad125efab24a3ec to your computer and use it in GitHub Desktop.
Making Ruby DSLs is incredibly simple... here's a small example.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
################################################################# | |
# The DSL | |
class DSL | |
attr_reader :props | |
def initialize(&block) | |
@props = {} | |
@handlers = {} | |
instance_eval &block | |
end | |
def set(name, value) | |
@props[name] = value | |
end | |
def on(event, &block) | |
@handlers[event] ||= [] | |
@handlers[event] << block | |
end | |
def handle_event(name) | |
if blocks = @handlers[name] | |
blocks.each { |block| instance_eval &block } | |
end | |
end | |
end | |
################################################################# | |
# Let's define our domain! | |
dsl = DSL.new do | |
set :donkeys, 5 | |
set :hamsters, 99999999 | |
on :face_plant do | |
puts "EIUUGGGHHHHHHH!!!!!!" | |
end | |
on :hamster_died do | |
puts "NOOOOOOOOOOOO! HAMMY!" | |
props[:hamsters] -= 1 | |
end | |
end | |
################################################################# | |
# Super sophisticated tests | |
puts dsl.props | |
dsl.handle_event :face_plant | |
dsl.handle_event :hamster_died | |
puts dsl.props |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{:donkeys=>5, :hamsters=>99999999} | |
EIUUGGGHHHHHHH!!!!!! | |
NOOOOOOOOOOOO! HAMMY! | |
{:donkeys=>5, :hamsters=>99999998} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment