delegates - Ruby: DRY class methods calling Singleton instance methods -
this question has answer here:
i have singleton class exchangeregistry
keeps exchange objects.
instead of needing call: exchangeregistry.instance.exchanges
i want able use: exchangeregistry.exchanges
this works, i'm not happy repetition:
require 'singleton' # ensure exchange created once class exchangeregistry include singleton # class methods ###### here duplication , 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
i'm not happy duplication in class methods.
i've tried using forwardable
, simpledelegator
can't seem dry out. (most examples out there not class methods instance methods)
the forwardable module this. since forwarding class methods, have open eigenclass , define forwarding there:
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"
Comments
Post a Comment