Ruby:调用Singleton实例方法的DRY类方法

Tom*_*ale 4 ruby singleton delegates

我有一个Singleton类ExchangeRegistry,它保留所有Exchange对象.

而不是需要打电话: ExchangeRegistry.instance.exchanges

我希望能够使用: ExchangeRegistry.exchanges

这有效,但我对重复不满意:

require 'singleton'

# Ensure an Exchange is only created once
class ExchangeRegistry
  include Singleton

  # Class Methods  ###### Here be duplication and dragons

  def self.exchanges
    instance.exchanges
  end

  def self.get(exchange)
    instance.get(exchange)
  end

  # Instance Methods

  attr_reader :exchanges

  def initialize
    @exchanges = {} # Stores every Exchange created
  end

  def get(exchange)
    @exchanges[Exchange.to_sym exchange] ||= Exchange.create(exchange)
  end
end
Run Code Online (Sandbox Code Playgroud)

我对类方法中的重复感到不满意.

我已经尝试使用ForwardableSimpleDelegator,但似乎无法得到这个干出来的.(大多数示例都不是类方法,而是例如方法)

Way*_*rad 5

可转发模块将执行此操作.由于您要转发类方法,您必须打开特征类并在那里定义转发:

require 'forwardable'
require 'singleton'

class Foo

  include Singleton

  class << self
    extend Forwardable
    def_delegators :instance, :foo, :bar
  end

  def foo
    'foo'
  end

  def bar
    'bar'
  end

end

p Foo.foo    # => "foo"
p Foo.bar    # => "bar"
Run Code Online (Sandbox Code Playgroud)