Module: MoreCoreExtensions::ObjectDeepSend

Defined in:
lib/more_core_extensions/core_ext/object/deep_send.rb

Instance Method Summary collapse

Instance Method Details

#deep_send(*args) ⇒ Object

Invokes the specified methods continuously, unless encountering a nil value.

10.deep_send("to_s.length")      # => 2
10.deep_send("to_s", "length")   # => 2
10.deep_send(:to_s, :length)     # => 2
10.deep_send(["to_s", "length"]) # => 2
[].deep_send("first.length")     # => nil

Raises:

  • (ArgumentError)


12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/more_core_extensions/core_ext/object/deep_send.rb', line 12

def deep_send(*args)
  args = args.first.dup if args.length == 1 && args.first.kind_of?(Array)
  args = args.shift.to_s.strip.split('.') + args

  arg = args.shift
  raise ArgumentError if arg.nil?

  result = send(arg)
  return nil    if result.nil?
  return result if args.empty?

  result.deep_send(args)
end