Sha256: d08adbfda2f58f41fba5fa209d3aa2d2b6f3b6079504c37cc0f2c4b422220aaf

Contents?: true

Size: 1.02 KB

Versions: 1

Compression:

Stored size: 1.02 KB

Contents

class JsonParser::Crawler
  include ConcernBuilder::OptionsParser

  attr_reader :post_process, :path

  delegate :case_type, :compact, to: :options_object

  def initialize(path, options = {}, &block)
    @options = options
    @path = path.map { |p| change_case(p) }
    @post_process = block
  end

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

    crawl(fetch(json, index), index + 1)
  end

  private

  def fetch(json, index)
    key = path[index]
    json.key?(key) ? json[key] : json[key.to_sym]
  end

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

  def wrap(json)
    post_process.call(json)
  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

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

Version data entries

1 entries across 1 versions & 1 rubygems

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