Module: Tins::Delegate

Included in:
Module
Defined in:
lib/tins/dslkit.rb

Overview

This module can be included into modules/classes to make the delegate method available.

Constant Summary collapse

UNSET =
Object.new.freeze

Instance Method Summary collapse

Instance Method Details

#delegate(method_name, opts = {}) ⇒ Object

A method to easily delegate methods to an object stored in an instance variable, class variable, constant, or returned by a method call.

Examples:

Delegate to an instance variable

class A
  extend Tins::Delegate
  delegate :method_here, to: :@obj
end

Delegate with an alias

class A
  extend Tins::Delegate
  delegate :method_here, to: :@obj, as: :method_there
end

Delegate to a method call result

class A
  extend Tins::Delegate
  delegate :method_here, to: :current_target
end

Parameters:

  • method_name (Symbol) —

    The method to delegate

  • opts (Hash) (defaults to: {}) —

    Configuration options

Options Hash (opts):

  • :to (String) —

    The delegation target: an instance variable ("@var"), class variable ("@@var"), constant ("SomeClass"), or method name

  • :as (Symbol) —

    Alias for the delegated method (defaults to method_name)

Raises:

  • (ArgumentError)


765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
# File 'lib/tins/dslkit.rb', line 765

def delegate(method_name, opts = {})
  to = opts[:to] || UNSET
  as = opts[:as] || method_name
  raise ArgumentError, "to argument wasn't defined" if to == UNSET
  to = to.to_s
  case
  when to[0, 2] == '@@'
    define_method(as) do |*args, &block|
      if self.class.class_variable_defined?(to)
        self.class.class_variable_get(to).__send__(method_name, *args, &block)
      end
    end
  when to[0] == ?@
    define_method(as) do |*args, &block|
      if instance_variable_defined?(to)
        instance_variable_get(to).__send__(method_name, *args, &block)
      end
    end
  when (?A..?Z).include?(to[0])
    define_method(as) do |*args, &block|
      Object.const_get(to).__send__(method_name, *args, &block)
    end
  else
    define_method(as) do |*args, &block|
      __send__(to).__send__(method_name, *args, &block)
    end
  end
end