Guest User

Untitled

a guest
Jun 20th, 2018
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.75 KB | None | 0 0
  1. class Module
  2. # has and after do not exist in Ruby OOTB, so we define them here:
  3. def has(options)
  4. options.each_pair do |k, v|
  5. singleton_class.send(:attr_accessor, k)
  6. instance_variable_set("@#{k}", v)
  7. end
  8. end
  9.  
  10. def after(meth, &after_block)
  11. old_meth = instance_method(meth)
  12. define_method(meth) do |*args, &block|
  13. old_meth.bind(self).(*args, &block)
  14. after_block.(self.class)
  15. end
  16. end
  17. end
  18.  
  19. module CountingModule
  20. def self.extended(c)
  21. c.has :count => 0
  22. c.after(:initialize) do |klass|
  23. puts "construction finished"
  24. klass.count += 1
  25. end
  26. end
  27. end
  28.  
  29. class Foo
  30. extend CountingModule
  31. end
  32.  
  33. Foo.new #=> "construction finished"
  34. Foo.new #=> "construction finished"
  35.  
  36. puts Foo.count #=> 2
Add Comment
Please, Sign In to add comment