Sha256: f81a9a699ccb77d8c9ee956a8ae0c8f5dc77fac4b379afb642e035b5411c7981

Contents?: true

Size: 1.57 KB

Versions: 3

Compression:

Stored size: 1.57 KB

Contents

class Eco::API::UseCases::Default::Utils::JsonToCsv < Eco::API::Common::Loaders::UseCase
  require_relative 'cli/json_to_csv_cli'

  name 'json-to-csv'
  type :other

  def main(*_args)
    return if simulate?

    CSV.open(out_filename, 'w') do |csv|
      csv << all_keys
      data.each do |item|
        csv << item.values_at(*all_keys)
      end
    ensure
      log(:info) {
        "Generated output file: '#{File.expand_path(out_filename)}'."
      }
    end
  end

  private

  def all_keys
    @all_keys ||= data.each_with_object([]) do |item, head|
      head.concat(item.keys - head)
    end
  end

  def data
    @data ||= parse_json_file.tap do |dt|
      ensure_array!(dt)

      log(:info) {
        "Loaded #{dt.count} items (from file '#{File.basename(input_file)}')"
      }

      exit 0 if simulate?
    end
  end

  def out_filename
    @out_filename ||= ''.then do
      input_basename = File.basename(input_file)
      base_name      = File.basename(input_basename, '.json')
      "#{base_name}.csv"
    end
  end

  def input_file
    options.dig(:source, :file)
  end

  def ensure_array!(data)
    return if data.is_a?(Array)

    msg = "Expecting JSON file to contain an Array. Given: #{data.class}"
    log(:error) { msg }
    raise msg
  end

  def parse_json_file(filename = input_file)
    fd = File.open(filename)
    JSON.load fd # rubocop:disable Security/JSONLoad
  rescue JSON::ParserError => err
    log(:error) { "Parsing error on file '#{filename}'" }
    raise err
  ensure
    fd&.close
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
eco-helpers-3.0.21 lib/eco/api/usecases/default/utils/json_to_csv_case.rb
eco-helpers-3.0.20 lib/eco/api/usecases/default/utils/json_to_csv_case.rb
eco-helpers-3.0.19 lib/eco/api/usecases/default/utils/json_to_csv_case.rb