Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Module
- # has and after do not exist in Ruby OOTB, so we define them here:
- def has(options)
- options.each_pair do |k, v|
- singleton_class.send(:attr_accessor, k)
- instance_variable_set("@#{k}", v)
- end
- end
- def after(meth, &after_block)
- old_meth = instance_method(meth)
- define_method(meth) do |*args, &block|
- old_meth.bind(self).(*args, &block)
- after_block.(self.class)
- end
- end
- end
- module CountingModule
- def self.extended(c)
- c.has :count => 0
- c.after(:initialize) do |klass|
- puts "construction finished"
- klass.count += 1
- end
- end
- end
- class Foo
- extend CountingModule
- end
- Foo.new #=> "construction finished"
- Foo.new #=> "construction finished"
- puts Foo.count #=> 2
Add Comment
Please, Sign In to add comment