Sha256: 4f9a450964e5d489cf3a817c847b621ec46096ba584dc9f4487071ab316704ed

Contents?: true

Size: 984 Bytes

Versions: 1

Compression:

Stored size: 984 Bytes

Contents

module JsonParser
  class Crawler
    attr_reader :post_process, :path, :case_type, :compact, :default

    def initialize(path:, case_type: :lower_camel, compact: false, default: nil, &block)
      @case_type = case_type
      @compact = compact
      @default = default
      @path = path
      @post_process = block
    end

    def value(json, index = 0)
      crawl(json, index)
    rescue Exception::KeyNotFound
      wrap(default)
    end

    private

    def crawl(json, index = 0)
      return wrap(json) if reader.is_ended?(index)
      return crawl_array(json, index) if json.is_a?(Array)

      crawl(reader.read(json, index), index + 1)
    end

    def reader
      @reader ||= JsonParser::Reader.new(
        path: path,
        case_type: case_type
      )
    end

    def wrap(json)
      post_process.call(json)
    end

    def crawl_array(array, index)
      array.map { |j| value(j, index) }.tap do |a|
        a.compact! if compact
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

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