Skip to content

Instantly share code, notes, and snippets.

@fcastellanos
Created August 12, 2011 00:47
Show Gist options
  • Save fcastellanos/1141197 to your computer and use it in GitHub Desktop.
Save fcastellanos/1141197 to your computer and use it in GitHub Desktop.
DSL Example in Ruby
def monthly_sales
110 # TODO: read the real number from the database
end
setup do
puts "Setting up target sales"
@target_sales = 100
end
event "monthly sales are suspiciously high" do
monthly_sales > @target_sales
end
event "monthly sales are abysmally low" do
monthly_sales < @target_sales
end
lambda {
setups = []
events = {}
Kernel.send :define_method, :event do |name, &block|
events[name] = block
end
Kernel.send :define_method, :setup do |&block|
setups << block
end
Kernel.send :define_method, :each_event do |&block|
events.each_pair do |name, event|
block.call name, event
end
end
Kernel.send :define_method, :each_setup do |&block|
setups.each do |setup|
block.call setup
end
end
}.call
Dir.glob('*events.rb').each do |file|
load file
each_event do |name, event|
env = Object.new
each_setup do |setup|
env.instance_eval &setup
end
puts "ALERT: #{name}" if env.instance_eval &event
end
end
event "the sky is falling" do
@sky_height < 300
end
event "it's getting closer" do
@sky_height < @mountains_height
end
setup do
puts "Setting up sky"
@sky_height = 100
end
setup do
puts "Setting up mountains"
@mountains_height = 200
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment