0

私のアプリケーションには、アプリケーション間で再利用されるシングルトンがあります。そのシングルトンがクラスからいくつかのデフォルト メソッドを取得するだけでなく、モジュール/固有クラスをカスタマイズできるようにしたいです。instance何よりも、すべての呼び出しでユーティリティ シングルトンを呼び出したくありません。

これが例です。私のデフォルトのクラスがUniverse::Earth. 次に、Earthそのクラスを「拡張」するモジュールがアプリケーションに必要です。

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

module Earth
  class < Universe::Earth << self; end

  grow!
end

それが実行さgrow!れると、NoMethodError.

これらのアプローチを試しました:

Class.new(Goodluck::Contest) << self
class < Universe::Earth << self; end
extend Universe::Earth

どうすれば機能しますか?

4

1 に答える 1

0

これはあなたが探しているものですか?

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)

:潮

于 2014-09-03T00:19:33.340 に答える