Created
November 2, 2010 01:25
-
-
Save banister/659149 to your computer and use it in GitHub Desktop.
Imitating Moose-like functionality for Ruby: as seen here http://www.perlmonks.org/?node_id=656019
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### Defining some Moose-like functionality | |
class Module | |
def has(options) | |
options.each_pair do |k, v| | |
singleton_class.send(:attr_accessor, k) | |
self.send("#{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 | |
def metaclass(name, &block) | |
Object.const_set(name, | |
Module.new do | |
define_singleton_method(:extended) do |klass| | |
klass.class_eval &block | |
end | |
end) | |
end | |
### End of moose-like functionality | |
metaclass :CountingModule do | |
has :count => 0 | |
after(:initialize) do |klass| | |
puts "construction finished" | |
klass.count += 1 | |
end | |
end | |
class Foo | |
extend CountingModule | |
end | |
Foo.new #=> "construction finished" | |
Foo.new #=> "construction finished" | |
puts Foo.count #=> 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment