Having a module singleton extending a class

280 Views Asked by At

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?

1

There are 1 best solutions below

1
On

Is this the sort of thing you are looking for?

module Universe
  class Earth
    def self.grow!
      @grown = true
    end
  end
end

module Earth
  Universe::Earth.class_eval do
    define_method(:instance_howdy) do
      puts "instance_howdy!"
    end
  end
  def (Universe::Earth).class_howdy
    puts "class_howdy!"
  end
end

Universe::Earth.methods(false)          #=> [:grow!, :class_howdy]
Universe::Earth.instance_methods(false) #=> [:instance_howdy]
Universe::Earth.new.instance_howdy      #=> instance_howdy!
Universe::Earth.class_howdy             #=> class_howdy!

[Edit: If you just want to set @grown => true, and retrieve it's value, you merely need:

module Earth
  Universe::Earth.grow! #=> true
end

Verify:

Universe::Earth.instance_variable_get("@grown") #=> true

If you wish to also add an accessor for the class instance variable, you could do this:

def add_class_accessor(c, accessor, var)  
  c.singleton_class.class_eval("#{accessor} :#{var}")
end

Universe::Earth.methods(false)
  #=> [:grow!]

module Earth
  Universe::Earth.grow! #=> true
  add_class_accessor(Universe::Earth, "attr_accessor", "grown")
end

Universe::Earth.methods(false)
  #=> [:grow!, :grown, :grown=]

Universe::Earth.grown
  #=> true
Universe::Earth.grown = "cat"
  #=> "cat"
Universe::Earth.grown
  #=> "cat"

Object#singleton_class was added in Ruby 1.9.2. For earlier versions you could do this:

def add_class_accessor(c, accessor, var)
  eigenclass = class << c; self; end
  eigenclass.class_eval("#{accessor} :#{var}")
end

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:

add_instance_method(klass, method, &block)
add_class_method(klass, method, &block)
add_instance_accessor(klass, accessor, var)

:tidE