Module: SleepingKingStudios::Tools::Toolbox::Delegator
- Defined in:
- lib/sleeping_king_studios/tools/toolbox/delegator.rb
Overview
Module for extending classes with basic delegation. Supports passing arguments, keywords, and blocks to the delegated method.
Instance Method Summary collapse
-
#delegate(*method_names, to: nil, allow_nil: false) ⇒ Object
Defines a wrapper method to delegate implementation of the specified method or methods to an object, to the object at another specified method, or to the object at a specified instance variable.
-
#wrap_delegate(target, klass: nil, except: [], only: []) ⇒ Object
Wraps a delegate object by automatically delegating each method that is defined on the delegate class from the instance to the delegate.
Instance Method Details
#delegate(*method_names, to: nil, allow_nil: false) ⇒ Object
Defines a wrapper method to delegate implementation of the specified method or methods to an object, to the object at another specified method, or to the object at a specified instance variable.
61 62 63 64 65 66 67 |
# File 'lib/sleeping_king_studios/tools/toolbox/delegator.rb', line 61 def delegate *method_names, to: nil, allow_nil: false raise ArgumentError.new('must specify a delegate') if to.nil? && !allow_nil method_names.each do |method_name| delegate_method method_name, to, { :allow_nil => !!allow_nil } end # each end |
#wrap_delegate(target, klass: nil, except: [], only: []) ⇒ Object
Wraps a delegate object by automatically delegating each method that is defined on the delegate class from the instance to the delegate. The delegate can be specified with an object literal or with the name of an instance method or instance variable.
Only methods that are defined at the time #wrap_delegate is called will be delegated, so make sure to call #wrap_delegate after loading any gems or libraries that extend your delegate class, such as ActiveSupport.
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 |
# File 'lib/sleeping_king_studios/tools/toolbox/delegator.rb', line 119 def wrap_delegate target, klass: nil, except: [], only: [] if klass.is_a?(Module) unless target.is_a?(String) || target.is_a?(Symbol) || target.is_a?(klass) raise ArgumentError.new "expected delegate to be a #{klass.name}" end # unless method_names = klass.instance_methods - Object.instance_methods elsif target.is_a?(String) || target.is_a?(Symbol) raise ArgumentError.new 'must specify a delegate class' else method_names = target.methods - Object.new.methods end # if-elsif-else if except.is_a?(Array) && !except.empty? method_names = method_names - except.map(&:intern) end # if if only.is_a?(Array) && !only.empty? method_names = method_names & only.map(&:intern) end # if delegate *method_names, :to => target end |