当前位置 : 主页 > 编程语言 > ruby >

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

来源:互联网 收集:自由互联 发布时间:2021-06-23
参见英文答案 Calling a method of a Ruby Singleton without the reference of ‘instance’5个 我有一个Singleton类ExchangeRegistry,它保存所有Exchange对象. 而不是需要打电话: ExchangeRegistry.instance.exchanges 我希
参见英文答案 > Calling a method of a Ruby Singleton without the reference of ‘instance’                                    5个
我有一个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

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

我已经尝试过使用Forwardable和SimpleDelegator,但似乎无法让它干掉. (大多数示例都不是类方法,而是例如方法)

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

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"
网友评论