Sha256: e8e08fbae99b5ac91c217c3bb23cd7f5706851229c054b0241a9ebd33435e2bd

Contents?: true

Size: 1.62 KB

Versions: 1

Compression:

Stored size: 1.62 KB

Contents

require "csv"

module FlatFile
  # Read data exports from Postico
  module QSV

    # https://ruby-doc.org/stdlib-2.6.1/libdoc/csv/rdoc/CSV.html#method-c-new
    # @return [Hash]
    OPTIONS = {
      col_sep:    ";",
      headers:    true,
      quote_char: "'",
      converters: ::CSV::Converters.keys + [:json],
    }.freeze()

    # @param filepath [String] Path to the file.
    # @return [Array<Hash{String => String}>]
    def self.from_file(filepath)
      # ::CSV::Converters[:json] = ->(s) { self.parse_postico_json(s) }
      return ::CSV.read(filepath, self.options).map(&:to_hash)
    end

    # @return [Hash]
    def self.options()
      custom_converter = ->(value, field_info) { self.parse_postico_json(value, field_info) }
      return {
        col_sep: ";",
        headers: true,
        quote_char: '"',
        converters: [custom_converter],
      }
    end

    # @param value [Object]
    # @param _field_info [Hash]
    # @return [Object]
    def self.parse_postico_json(value, _field_info)
      return value if value.nil?()
      return value if value.length == 0
      return value unless value[0] == "{"
      return ::JSON.parse(value)
    rescue ::JSON::ParserError => e
      # if defined?(Rails)
      #   Rails.logger.error({
      #     message: "Rescued from 'JSON::ParserError' in parse_postico_json",
      #     error: e,
      #   })
      # end
      return value
    rescue StandardError => e
      # if defined?(Rails)
      #   Rails.logger.error({
      #     message: "Rescued from 'StandardError' in parse_postico_json",
      #     error: e,
      #   })
      # end
      return value
    end

  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
flat_file-0.3.0 lib/flat_file/qsv.rb