Sha256: 773edfedd58e217396206a2f5687b16cc50a2ad0303bfbfae446a79db10e0b66

Contents?: true

Size: 814 Bytes

Versions: 4

Compression:

Stored size: 814 Bytes

Contents

module MoreCoreExtensions
  module ObjectDeepSend
    #
    # 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
    #
    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
  end
end

Object.send(:include, MoreCoreExtensions::ObjectDeepSend)

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
more_core_extensions-4.5.0 lib/more_core_extensions/core_ext/object/deep_send.rb
more_core_extensions-4.4.0 lib/more_core_extensions/core_ext/object/deep_send.rb
more_core_extensions-4.3.1 lib/more_core_extensions/core_ext/object/deep_send.rb
more_core_extensions-4.3.0 lib/more_core_extensions/core_ext/object/deep_send.rb