Sha256: ec5fca29f516958134b8bfc76542bd5f6bdd1f273afb024352e0036603c20264

Contents?: true

Size: 824 Bytes

Versions: 1

Compression:

Stored size: 824 Bytes

Contents

module JsonParser
  class Reader
    attr_reader :path, :case_type

    def initialize(path:, case_type:)
      @case_type = case_type
      @path = path.map(&self.method(:change_case))
    end

    def read(json, index)
      key = path[index]

      check_key!(json, key)

      json.key?(key) ? json[key] : json[key.to_sym]
    end

    def is_ended?(index)
      index >= path.size
    end

    private

    def check_key!(json, key)
      return if has_key?(json, key)
      raise Exception::KeyNotFound
    end

    def has_key?(json, key)
      json&.key?(key) || json&.key?(key.to_sym)
    end

    def change_case(key)
      case case_type
      when :lower_camel
        key.camelize(:lower)
      when :upper_camel
        key.camelize(:upper)
      when :snake
        key.underscore
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
json_parser-1.3.1 lib/json_parser/reader.rb