Hello rubyists,
I'm pretty sure what I want to do isn't possible, but I thought I'd ask
here before moving on to other approaches. I have a base class that does
some things to subclasses using Class#inherited, and it would be ideal if
the code could react to optional settings that can be configured in the
subclass declaration.
Some illustrative sample code, adapted from the Class#inherited
documentation:
class Foo
class << self
attr_accessor :opt
def inherited(subclass)
puts "New subclass: #{subclass}"
puts "The cow goes #{opt}"
end
end
self.opt = :foo
end
class Bar < Foo
self.opt = :bar
end
class Baz < Foo
end
Output:
New subclass: Bar
The cow goes foo
New subclass: Baz
The cow goes foo
Desired output:
New subclass: Bar
The cow goes bar
New subclass: Baz
The cow goes foo
I'm not too worried what the syntax looks like; the attr_accessor could be
replaced with a method that subclasses can override, or some sort of DSL. I
suspect however that Class#inherited is called before any code in the
subclass declaration is executed, which I guess means I'm out of luck. Is
there any documentation or source code describing the inheritance process
that I could read to give me closure?
Or maybe there's another way of doing what I want? Another illustrative
example that's a bit closer to my actual code.
What I'd like to do:
def self.inherited(subclass)
if subclass.thing_enabled?
define_method(inferred_name) { do_the_thing }
else
define_method(inferred_name) { do_something_else }
end
end
What I'd like to avoid:
def self.inherited(subclass)
define_method(inferred_name) do
if thing_enabled?
do_the_thing
else
do_something_else
end
end
end
The class itself is passed on to another gem and never instantiated, so any
clever tricks during object initialization probably aren't applicable.
Ideas? Any input would be greatly appreciated.
Thanks,
Doug