Class: TypeCoercer

Inherits:
Object
  • Object
show all
Includes:
ActionView::Helpers::NumberHelper
Defined in:
lib/type_coercer.rb

Overview

Best-effort string→native-Ruby coercer: takes any user-supplied value
(typically from CSV import or arbitrary-text JSON columns) and
returns it as Integer / Float / true / false / squished String / nil
depending on what the input looks like. Blank inputs become nil.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ TypeCoercer

Returns a new instance of TypeCoercer.



11
12
13
# File 'lib/type_coercer.rb', line 11

def initialize(options = {})
  @options = options
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



9
10
11
# File 'lib/type_coercer.rb', line 9

def options
  @options
end

Class Method Details

.coerce(value, options = {}) ⇒ Object



15
16
17
# File 'lib/type_coercer.rb', line 15

def self.coerce(value, options = {})
  new(options).coerce(value)
end

Instance Method Details

#coerce(value) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/type_coercer.rb', line 19

def coerce(value)
  strVal = value.to_s.squish
  precision = options[:precision] || 4
  begin
    strVal = number_with_precision(strVal, precision: precision, strip_insignificant_zeros: true, raise: true)
    value_casted = begin
      Integer(strVal)
    rescue StandardError
      nil
    end
    value_casted ||= begin
      Float(strVal)
    rescue StandardError
      nil
    end
    value_casted = true if value_casted.nil? && %w[t true y yes].include?(strVal)
    value_casted = false if value_casted.nil? && %w[f false n no].include?(strVal)
  rescue InvalidNumberError
    # Do nothing
  end
  value_casted ||= strVal # fallback on string
  value_casted.presence # Blanks become nils
end