class Object

Public Instance Methods

nested_send(attribute, with_indifferent_access: false) click to toggle source
# File lib/nested_send.rb, line 40
def nested_send(attribute, with_indifferent_access: false)

  checker = NestedSend::Checker

  matches = /([^\.\[\]]+)(.*)/.match(attribute)
  attribute = matches.captures[0]
  object = send(attribute)

  until matches.captures[1].empty?

    next_part = matches.captures[1]
    kind = checker.kind_of_attribute(next_part.slice!(0))

    if kind == :method

      matches = /([^\.\[\]]+)(.*)/.match(next_part)
      attribute = matches.captures[0]
      object = object.send(attribute)

    elsif kind == :collection

      matches = /(['|"|:]*[^\]]+['|"]*)\](.*)/.match(next_part)
      attribute = matches.captures[0]

      type = checker.kind_of_collection(attribute)
      raise ArgumentError, "Provided attribute was unable to be parsed: #{attribute}" unless type

      if type == :sym_hash
        attribute.slice!(0)
        attribute = attribute.to_sym
      elsif type == :str_hash
        attribute.slice!(0)
        attribute.chop!
      elsif type == :array
        attribute = attribute.to_i
      end

      if with_indifferent_access && object.is_a?(Hash)
        object = object.with_indifferent_access
      end

      object = object[attribute]

    else
      raise ArgumentError, "Could not parse attribute: #{attribute}"
    end

  end

  object
end