2

Rubyのシングルトンが好きだけどもっとうまく使いこなしたいので例

require 'singleton'

class Foo
  include Singleton

  def initialize
    # code to setup singleton here 
  end

  def self.get_bar
    Foo.instance.get_bar
  end

  def get_bar
  end

  def get_nar
  end
end

使用法

Foo.instance.get_bar(デフォルト)またはFoo.get_bar(私が作成した静的self.get_barメソッドのため)

メソッドごとに静的ラッパーを作成しなくても、すべてのメソッドにアクセスできるようにするエレガントな方法はありますか? メソッドごとに書く必要があるのは冗長に思えます.instance

アップデート

ルビー 1.8.7

4

2 に答える 2

3

このモジュールを混在させることができます:

module DelegateToSingleton

  def respond_to_missing?(method)
    super || instance.respond_to?(method)
  end

  def method_missing(method, *args)
    instance.send(method, *args)
  end

end

あなたのシングルトンに:

class Foo

  extend DelegateToSingleton
  include Singleton

  def foo
    'foo'
  end

  def bar
    'bar'
  end

end

これらの結果:

p Foo.foo    # => "foo"
p Foo.bar    # => "bar"

DelegateToSingleton::method_missingFoo が知らないメソッドを受け取るたびに、それをそのインスタンスに転送するだけです。

DelegateToSingleton::respond_to_missing?厳密に必要というわけではありませんが、method_missing を使っていたずらをするときは常に持っておくと良いマナーです。

1.9.2 より前の Ruby の場合:代わりにオーバーライドrespond_to?respond_to_missing?

于 2012-09-06T15:43:09.927 に答える
3

インスタンスからクラスを分離するだけです。

class Foo
  def initialize 
  end

  def get_bar
  end

  def get_nar
  end
end

MyFoo = Foo.new
MyFoo.get_bar
于 2012-09-06T13:24:29.350 に答える