/ Published in: Ruby
Execute an instance method of Object, call in its block class methods of another object and call in the blocks of that methods class or instance methods of the object depending on if the block applies to a macros or to a simple class method.
Expand |
Embed | Plain Text
# encoding: utf-8 ##################### # The Example Class # ##################### class Example def self.execute(&block) class_eval(&block) end def self.some_code(&block) new.instance_eval(&block) end end ##################### # Object Extensions # ##################### module ObjectExtensions def execute(&block) Example.execute(&block) end end ################################### # Instance Extensions for Example # ################################### module ExampleInstanceExtensions def one 'one' end def two 'two' end def three 'three' end end ######################## # Macroses for Example # ######################## module ExampleClassExtensions def do_one some_code do "do #{one}" end end def do_two some_code do "do #{two}" end end def do_three some_code do "do #{three}" end end def the_macros yield end end Object.__send__(:include, ObjectExtensions) Example.__send__(:extend, ExampleClassExtensions) Example.__send__(:include, ExampleInstanceExtensions) ##################### # The Demonstration # ##################### puts "The #{self} scope." #=> main some_code rescue puts 'some_code boom!' #=> some_code boom! one rescue puts 'one boom!' #=> one boom! two rescue puts 'two boom!' #=> two boom! three rescue puts 'three boom!' #=> three boom! execute do the_macros do puts "The #{self} scope." #=> the Example class puts do_one, #=> do one do_two, #=> do two do_three #=> do three end some_code do puts "The #{self} scope." #=> an Example instance puts one, #=> one two, #=> two three #=> three end execute do some_code do puts "The #{self} scope." #=> an Example instance. puts one, #=> one two, #=> two three #=> three end end puts "The #{self} scope." #=> the Example class one rescue puts 'one again boom!' #=> one again boom! two rescue puts 'two again boom!' #=> two again boom! three rescue puts 'three again boom!' #=> three again boom! end
You need to login to post a comment.
