module Kind::Dig

Public Instance Methods

[](*keys) click to toggle source
# File lib/kind/dig.rb, line 35
def [](*keys)
  ->(data) { call!(data, keys) }
end
call(data, *input) { |result| ... } click to toggle source
# File lib/kind/dig.rb, line 21
def call(data, *input)
  args = input.size == 1 && input[0].kind_of?(::Array) ? input[0] : input

  result = call!(data, args)

  return result unless block_given?

  yield(result) unless KIND.nil_or_undefined?(result)
end
call!(data, keys = Empty::ARRAY) click to toggle source
# File lib/kind/dig.rb, line 11
def call!(data, keys = Empty::ARRAY) # :nodoc
  keys.reduce(data) do |memo, key|
    value = get(memo, key)

    break if KIND.nil_or_undefined?(value)

    value
  end
end
presence(*args, &block) click to toggle source
# File lib/kind/dig.rb, line 31
def presence(*args, &block)
  Presence.(call(*args, &block))
end

Private Instance Methods

get(data, key) click to toggle source
# File lib/kind/dig.rb, line 41
def get(data, key)
  return data[key] if ::Hash === data

  case data
  when ::Array
    data[key] if key.respond_to?(:to_int)
  when ::OpenStruct
    data[key] if key.respond_to?(:to_sym)
  when ::Struct
    data[key] rescue nil if key.respond_to?(:to_int) || key.respond_to?(:to_sym)
  else
    data.public_send(key) if key.respond_to?(:to_sym) && data.respond_to?(key)
  end
end