如何将Ruby中调用Singleton实例方法的DRY类方法改写成长尾词?

2026-04-11 14:441阅读0评论SEO问题
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计331个文字,预计阅读时间需要2分钟。

如何将Ruby中调用Singleton实例方法的DRY类方法改写成长尾词?

在Ruby中调用Singleton类的实例方法时,不需要直接引用实例。例如,对于名为`ExchangeRegistry`的Singleton类,可以直接使用`ExchangeRegistry.instance.method_name`来调用其方法,而不需要`instance`关键字。例如:

ExchangeRegistry.instance.exchanges

参见英文答案 > Calling a method of a Ruby Singleton without the reference of ‘instance’5个
我有一个Singleton类ExchangeRegistry,它保存所有Exchange对象.

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

我希望能够使用:
ExchangeRegistry.exchanges

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

如何将Ruby中调用Singleton实例方法的DRY类方法改写成长尾词?

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"

标签:DRY

本文共计331个文字,预计阅读时间需要2分钟。

如何将Ruby中调用Singleton实例方法的DRY类方法改写成长尾词?

在Ruby中调用Singleton类的实例方法时,不需要直接引用实例。例如,对于名为`ExchangeRegistry`的Singleton类,可以直接使用`ExchangeRegistry.instance.method_name`来调用其方法,而不需要`instance`关键字。例如:

ExchangeRegistry.instance.exchanges

参见英文答案 > Calling a method of a Ruby Singleton without the reference of ‘instance’5个
我有一个Singleton类ExchangeRegistry,它保存所有Exchange对象.

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

我希望能够使用:
ExchangeRegistry.exchanges

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

如何将Ruby中调用Singleton实例方法的DRY类方法改写成长尾词?

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"

标签:DRY