Sha256: 2c9b5ce820c6d0d55fa926ca1fd27c4b6a54876abbfdae66e3cb2ef77ce9c77c

Contents?: true

Size: 1.53 KB

Versions: 6

Compression:

Stored size: 1.53 KB

Contents

require 'active_support/core_ext/hash'
require 'active_support/core_ext/object/blank'
class Topographer::Importer::Mapper::FieldMapping
  attr_reader :input_columns, :output_field

  def initialize(required, input_columns, output_field, &mapping_behavior)
    @required = required
    @input_columns = Array(input_columns)
    @output_field = output_field
    @mapping_behavior = mapping_behavior
    @invalid_keys = []
  end

  def process_input(input, result)
    mapping_input = input.slice(*input_columns)
    @invalid_keys = get_invalid_keys(mapping_input)
    data = (@invalid_keys.any?) ? nil : apply_mapping(mapping_input)
    if !data.nil?
      result.add_data(output_field, data)
    elsif required?
      result.add_error(output_field, invalid_input_error)
    end

  rescue => exception
    result.add_error(output_field, exception.message)

  end

  def required?
    @required
  end

  private

  def apply_mapping(mapping_input)
    if @mapping_behavior
      @mapping_behavior.(mapping_input)
    else
      (mapping_input.size > 1) ? mapping_input.values.join(', ') : mapping_input.values.first
    end
  end

  def invalid_input_error
    "Missing required input(s): `#{@invalid_keys.join(", ")}` for `#{@output_field}`"
  end

  def get_invalid_keys(input)
    missing_columns = @input_columns - input.keys
    #reject input that is not blank or the value `false`
    #this allows boolean inputs for required fields
    missing_data = @required ? input.reject{|k,v| !v.blank? || v == false }.keys : []
    missing_columns + missing_data
  end

end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
topographer-0.0.7 lib/topographer/importer/mapper/field_mapping.rb
topographer-0.0.6 lib/topographer/importer/mapper/field_mapping.rb
topographer-0.0.5 lib/topographer/importer/mapper/field_mapping.rb
topographer-0.0.4 lib/topographer/importer/mapper/field_mapping.rb
topographer-0.0.3 lib/Topographer/importer/mapper/field_mapping.rb
topographer-0.0.2 lib/Topographer/importer/mapper/field_mapping.rb