これはあなたが探しているものですか?
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!
[編集:を設定@grown => true
し、その値を取得するだけの場合は、次のものが必要です。
module Earth
Universe::Earth.grow! #=> true
end
確認:
Universe::Earth.instance_variable_get("@grown") #=> true
クラス インスタンス変数のアクセサも追加する場合は、次のようにします。
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は Ruby 1.9.2 で追加されました。以前のバージョンでは、これを行うことができました:
def add_class_accessor(c, accessor, var)
eigenclass = class << c; self; end
eigenclass.class_eval("#{accessor} :#{var}")
end
add_class_accessor
必要に応じてモジュールを含めることを検討してください。同じモジュールに追加できる他のメソッドは次のとおりです。
add_instance_method(klass, method, &block)
add_class_method(klass, method, &block)
add_instance_accessor(klass, accessor, var)
:潮