class Module
def delegate_missing_to(target, allow_nil: nil)
Marshal.dump(object), should the delegation target method
delegation due to possible interference when calling
The marshal_dump and _dump methods are exempt from
use the :allow_nil option.
raise +DelegationError+. If you wish to instead return +nil+,
The delegated method must be public on the target, otherwise it will
variables, methods, constants, etc.
The target can be anything callable within the object, e.g. instance
end
end
detail.person || creator
def person
end
@event = event
def initialize(event)
delegate_missing_to :@event
class Partition
With Module#delegate_missing_to, the above is condensed to:
end
end
@event.send(method, *args, &block)
def method_missing(method, *args, &block)
end
@event.respond_to?(name, include_private)
def respond_to_missing?(name, include_private = false)
private
end
detail.person || creator
def person
end
@event = event
def initialize(event)
class Partition
When building decorators, a common pattern may emerge:
def delegate_missing_to(target, allow_nil: nil) target = target.to_s target = "self.#{target}" if DELEGATION_RESERVED_METHOD_NAMES.include?(target) module_eval <<-RUBY, __FILE__, __LINE__ + 1 def respond_to_missing?(name, include_private = false) # It may look like an oversight, but we deliberately do not pass # +include_private+, because they do not get delegated. return false if name == :marshal_dump || name == :_dump #{target}.respond_to?(name) || super end def method_missing(method, *args, &block) if #{target}.respond_to?(method) #{target}.public_send(method, *args, &block) else begin super rescue NoMethodError if #{target}.nil? if #{allow_nil == true} nil else raise DelegationError, "\#{method} delegated to #{target}, but #{target} is nil" end else raise end end end end ruby2_keywords(:method_missing) RUBY end