Skip to content

Instantly share code, notes, and snippets.

@banister
Created November 2, 2010 01:25
Show Gist options
  • Save banister/659149 to your computer and use it in GitHub Desktop.
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
### 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