I have a singleton in my application that gets reused across applications. I want that singleton to get some default methods from my class, but also be able to customize the module/eigenclass. Most of all, I don't want to call up instance
on every call the the utility singleton.
Here's an example. Let's say my default class is Universe::Earth
. Then I want an Earth
module in my application that "extends" that class.
module Universe
class Earth
def self.grow!
@grown = true
end
end
end
module Earth
class < Universe::Earth << self; end
grow!
end
When that's run, grow!
is a NoMethodError
.
Tried those approaches:
Class.new(Goodluck::Contest) << self
class < Universe::Earth << self; end
extend Universe::Earth
How do I make it work?
Is this the sort of thing you are looking for?
[Edit: If you just want to set
@grown => true
, and retrieve it's value, you merely need:Verify:
If you wish to also add an accessor for the class instance variable, you could do this:
Object#singleton_class was added in Ruby 1.9.2. For earlier versions you could do this:
You might consider putting
add_class_accessor
in a module to be included as needed. Other methods you might add to the same module might be::tidE