Class: TypeCoercer

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ TypeCoercer

Returns a new instance of TypeCoercer.



6
7
8
# File 'lib/type_coercer.rb', line 6

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

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



4
5
6
# File 'lib/type_coercer.rb', line 4

def options
  @options
end

Class Method Details

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



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

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

Instance Method Details

#coerce(value) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/type_coercer.rb', line 14

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 = (Integer(strVal) rescue nil)
    value_casted ||= (Float(strVal) rescue nil)
    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 => exc
    # Do nothing
  end
  value_casted ||= strVal #fallback on string
  value_casted.presence #Blanks become nils
end