Skip to content

Instantly share code, notes, and snippets.

@banister
Created November 1, 2010 23:15
Show Gist options
  • Save banister/659041 to your computer and use it in GitHub Desktop.
Save banister/659041 to your computer and use it in GitHub Desktop.
Perl moose examples in Ruby
# Perl Moose example in Ruby, Perl code found here: http://www.perlmonks.org/?node_id=656019
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
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
class Foo
has :count => 0
after(:initialize) do |klass|
puts "after construction"
klass.count += 1
end
end
Foo.new
Foo.new
puts Foo.count #=> 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment