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
Instance Method Summary collapse
-
#delegate(method_name, opts = {}) ⇒ Object
A method to easily delegate methods to an object, stored in an instance variable or returned by a method call.
Instance Method Details
#delegate(method_name, opts = {}) ⇒ Object
A method to easily delegate methods to an object, stored in an instance variable or returned by a method call.
It’s used like this:
class A
delegate :method_here, :@obj, :method_there
end
or:
class A
delegate :method_here, :method_call, :method_there
end
other_method_name defaults to method_name, if it wasn’t given. def delegate(method_name, to: UNSET, as: method_name)
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 |
# File 'lib/tins/dslkit.rb', line 437 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| self.class.class_variable_get(to).__send__(method_name, *args, &block) end when to[0] == ?@ define_method(as) do |*args, &block| instance_variable_get(to).__send__(method_name, *args, &block) end when (?A..?Z).include?(to[0]) define_method(as) do |*args, &block| Tins::DeepConstGet.deep_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 |