Sha256: 444467573a0337304c0ee800c5b2dc8ca9e5fa73da21e3877616512180660878

Contents?: true

Size: 825 Bytes

Versions: 1

Compression:

Stored size: 825 Bytes

Contents

# frozen_string_literal: true

module Kind
  module Dig
    extend self

    def call(data, keys)
      return unless keys.is_a?(::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

1 entries across 1 versions & 1 rubygems

Version Path
kind-4.0.0 lib/kind/dig.rb