Module: SmarterCSV::HashTransformations

Included in:
Reader
Defined in:
lib/smarter_csv/hash_transformations.rb

Instance Method Summary collapse

Instance Method Details

#hash_transformations(hash, options) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/smarter_csv/hash_transformations.rb', line 5

def hash_transformations(hash, options)
  # there may be unmapped keys, or keys purposedly mapped to nil or an empty key..
  # make sure we delete any key/value pairs from the hash, which the user wanted to delete:
  remove_empty_values = options[:remove_empty_values] == true
  remove_zero_values = options[:remove_zero_values]
  remove_values_matching = options[:remove_values_matching]
  convert_to_numeric = options[:convert_values_to_numeric]
  value_converters = options[:value_converters]

  hash.each_with_object({}) do |(k, v), new_hash|
    next if k.nil? || k == '' || k == :""
    next if remove_empty_values && (has_rails ? v.blank? : blank?(v))
    next if remove_zero_values && v.is_a?(String) && v =~ /^(0+|0+\.0+)$/ # values are Strings
    next if remove_values_matching && v =~ remove_values_matching

    # deal with the :only / :except options to :convert_values_to_numeric
    if convert_to_numeric && !limit_execution_for_only_or_except(options, :convert_values_to_numeric, k)
      if v =~ /^[+-]?\d+\.\d+$/
        v = v.to_f
      elsif v =~ /^[+-]?\d+$/
        v = v.to_i
      end
    end

    converter = value_converters[k] if value_converters
    v = converter.convert(v) if converter

    new_hash[k] = v
  end
end