Execute an instance method of Object and call in its block instance methods of another object


/ Published in: Ruby
Save to your folder(s)



Copy this code and paste it in your HTML
  1. # encoding: utf-8
  2.  
  3. module ObjectExtensions
  4. def execute(&block)
  5. Extension.new.execute(&block)
  6. end
  7. end
  8.  
  9. class Extension
  10. def execute(&block)
  11. self.instance_eval(&block)
  12. end
  13.  
  14. def one; puts 'one' end
  15. def two; puts 'two' end
  16. def three; puts 'three' end
  17. end
  18.  
  19. Object.__send__(:include, ObjectExtensions)
  20.  
  21. one rescue puts 'boom!' #=> boom!
  22. two rescue puts 'boom too!' #=> boom too!
  23. three rescue puts 'boom three!' #=> boom three!
  24.  
  25. execute do
  26. one #=> one
  27. two #=> two
  28. three #=> three
  29. four rescue puts 'boom four!' #=> boom four!
  30. end

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.