Class: TypeCoercer
- Inherits:
-
Object
- Object
- TypeCoercer
- 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
-
#options ⇒ Object
readonly
Returns the value of attribute options.
Class Method Summary collapse
-
.coerce(value, options = {}) ⇒ Integer, ...
The coerced value.
Instance Method Summary collapse
-
#coerce(value) ⇒ Integer, ...
The coerced value (nil for blanks).
-
#initialize(options = {}) ⇒ TypeCoercer
constructor
A new instance of TypeCoercer.
Constructor Details
#initialize(options = {}) ⇒ TypeCoercer
Returns a new instance of TypeCoercer.
13 14 15 |
# File 'lib/type_coercer.rb', line 13 def initialize( = {}) @options = end |
Instance Attribute Details
#options ⇒ Object (readonly)
Returns the value of attribute options.
9 10 11 |
# File 'lib/type_coercer.rb', line 9 def @options end |
Class Method Details
.coerce(value, options = {}) ⇒ Integer, ...
Returns the coerced value.
21 22 23 |
# File 'lib/type_coercer.rb', line 21 def self.coerce(value, = {}) new().coerce(value) end |
Instance Method Details
#coerce(value) ⇒ Integer, ...
Returns the coerced value (nil for blanks).
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
# File 'lib/type_coercer.rb', line 26 def coerce(value) strVal = value.to_s.squish precision = [: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 |