Sha256: bdc3c0db37d61f56ee45c05993373dabbca5cce97c843f732b38266d30479c6a

Contents?: true

Size: 823 Bytes

Versions: 2

Compression:

Stored size: 823 Bytes

Contents

module Arstotzka
  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

2 entries across 2 versions & 1 rubygems

Version Path
arstotzka-1.0.1 lib/arstotzka/reader.rb
arstotzka-1.0.0 lib/arstotzka/reader.rb