Sha256: 8998ea7576176886e4f5854b68876cc91867ffe4ff0feecd7ca515d90e4b13e5

Contents?: true

Size: 882 Bytes

Versions: 14

Compression:

Stored size: 882 Bytes

Contents

# frozen_string_literal: true

module Openapi3Parser
  class CautiousDig
    private_class_method :new

    def self.call(*args)
      new.call(*args)
    end

    def call(collection, *segments)
      segments.inject(collection) do |next_depth, segment|
        break unless next_depth

        if next_depth.respond_to?(:keys)
          hash_like(next_depth, segment)
        elsif next_depth.respond_to?(:[])
          array_like(next_depth, segment)
        end
      end
    end

    private

    def hash_like(item, segment)
      key = item.keys.find { |k| segment == k || segment.to_s == k.to_s }
      item[key]
    end

    def array_like(item, segment)
      index = if segment.is_a?(String) && segment =~ /\A\d+\z/
                segment.to_i
              else
                segment
              end
      index.is_a?(Integer) ? item[index] : nil
    end
  end
end

Version data entries

14 entries across 14 versions & 2 rubygems

Version Path
openapi3_parser-0.10.1 lib/openapi3_parser/cautious_dig.rb
openapi3_parser-0.9.2 lib/openapi3_parser/cautious_dig.rb
mountapi-0.11.1 vendor/bundle/ruby/2.7.0/gems/openapi3_parser-0.9.1/lib/openapi3_parser/cautious_dig.rb
openapi3_parser-0.9.1 lib/openapi3_parser/cautious_dig.rb
openapi3_parser-0.9.0 lib/openapi3_parser/cautious_dig.rb
openapi3_parser-0.8.2 lib/openapi3_parser/cautious_dig.rb
openapi3_parser-0.8.1 lib/openapi3_parser/cautious_dig.rb
openapi3_parser-0.8.0 lib/openapi3_parser/cautious_dig.rb
openapi3_parser-0.7.0 lib/openapi3_parser/cautious_dig.rb
openapi3_parser-0.6.1 lib/openapi3_parser/cautious_dig.rb
openapi3_parser-0.6.0 lib/openapi3_parser/cautious_dig.rb
openapi3_parser-0.5.2 lib/openapi3_parser/cautious_dig.rb
openapi3_parser-0.5.1 lib/openapi3_parser/cautious_dig.rb
openapi3_parser-0.5.0 lib/openapi3_parser/cautious_dig.rb