|
|
|
|
|
by jnicklas
6503 days ago
|
|
I am not entirely sure what you mean, but adding or removing methods from Ruby classes is extremely simple and there are a number of hooks in place that allow you to play with the class definition on inheritance. But here is another example of the power of Ruby metaprogramming. The example is sort of nuts, but something similar is actually used in the Camping microwebframework. Blah = {
:foo => proc { puts "foo" },
:bar => proc { puts "bar" },
:baz => proc { puts "baz" }
}
def Monkey(method)
klass = Class.new
klass.class_eval do
define_method :shout do
Blah[method].call
end
end
return klass
end
class Chimp < Monkey(:foo)
end
class Gorilla < Monkey(:bar)
end
a = Chimp.new
a.shout # => "foo"
b = Gorilla.new
b.shout # => "bar"
Blah[:foo] = proc { puts "I have changed" }
a.shout # => "I have changed"
|
|
What I'm looking for is something equivalent to Python's "metaclass" declaration, which lets you completely control the way the class object is created. I've been told by fairly knowledgeable Rubyists that there isn't really an equivalent, and that after-the-fact monkeypatching or factory solutions like yours are the only way to come at the problem in Ruby.