Sha256: 41f4267af14d83bc89e68806dfa8d8582e499de4833b649b89f69d70eb7c3a1b

Contents?: true

Size: 828 Bytes

Versions: 3

Compression:

Stored size: 828 Bytes

Contents

# frozen_string_literal: true

module Kind
  module Dig
    extend self

    def call(data, keys)
      return unless keys.kind_of?(::Array)

      keys.reduce(data) do |memo, key|
        value = get(memo, key)

        break if KIND.null?(value)

        value
      end
    end

    def [](*keys)
      ->(data) { call(data, keys) }
    end

    private

      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
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
kind-5.1.0 lib/kind/core/dig.rb
kind-5.0.0 lib/kind/dig.rb
kind-4.1.0 lib/kind/dig.rb