Skip to content

Instantly share code, notes, and snippets.

@aninder
Created March 5, 2013 12:05
Show Gist options
  • Save aninder/5089886 to your computer and use it in GitHub Desktop.
Save aninder/5089886 to your computer and use it in GitHub Desktop.
fix for bug in "metaprogramming ruby" book code snippet on page 121 (creating DSL). It calls events of previous files again for each new file loaded and redflag2.rb is another way creating it.
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('*event*.rb').each do |file|
load file
end
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
lambda {
event = {}
setup = []
Object.class_eval do
define_method :event do |name,&block|
event[name]=block
end
end
Object.class_eval do
define_method :setup do |&block|
setup << block
end
end
Dir.glob('*event*.rb').each do |file|
event={}
setup=[]
puts "====>>>found #{file}"
load file
event.each_pair do |eventName,eventy|
puts "---setting clean room for--------->#{eventName}"
o=Object.new
setup.each do |block|
o.instance_eval &block
end
puts "ALERT #{eventName}" if o.instance_eval &eventy
end
end
}.call
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment