Class: LcpRuby::Import::ValueCoercer
- Inherits:
-
Object
- Object
- LcpRuby::Import::ValueCoercer
- Defined in:
- lib/lcp_ruby/import/value_coercer.rb
Defined Under Namespace
Classes: CoercionError
Constant Summary collapse
- DEFAULT_BOOLEAN_TRUE =
%w[true yes 1 t ano].freeze
- DEFAULT_BOOLEAN_FALSE =
%w[false no 0 f ne].freeze
Instance Method Summary collapse
-
#coerce(value, field_def) ⇒ Object
Coerce a string value to the target field type.
-
#initialize(parsing_options = {}) ⇒ ValueCoercer
constructor
A new instance of ValueCoercer.
Constructor Details
#initialize(parsing_options = {}) ⇒ ValueCoercer
Returns a new instance of ValueCoercer.
9 10 11 12 13 14 15 16 |
# File 'lib/lcp_ruby/import/value_coercer.rb', line 9 def initialize( = {}) @parsing_options = || {} @decimal_separator = @parsing_options["decimal_separator"] || "." @boolean_true = Array(@parsing_options["boolean_true"] || DEFAULT_BOOLEAN_TRUE).map(&:to_s).map(&:downcase) @boolean_false = Array(@parsing_options["boolean_false"] || DEFAULT_BOOLEAN_FALSE).map(&:to_s).map(&:downcase) @date_formats = Array(@parsing_options["date_format"] || [ "%Y-%m-%d" ]) @datetime_formats = Array(@parsing_options["datetime_format"] || [ "%Y-%m-%dT%H:%M:%S" ]) end |
Instance Method Details
#coerce(value, field_def) ⇒ Object
Coerce a string value to the target field type. Returns the coerced value, or raises CoercionError.
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/lcp_ruby/import/value_coercer.rb', line 20 def coerce(value, field_def) return nil if value.nil? || (value.is_a?(String) && value.strip.empty?) value = value.to_s.strip if value.is_a?(String) base_type = field_def.respond_to?(:resolved_base_type) ? field_def.resolved_base_type : field_def.type case base_type when "string", "text", "email", "phone", "url", "color" value.to_s when "integer" coerce_integer(value, field_def) when "float" coerce_float(value, field_def) when "decimal" coerce_decimal(value, field_def) when "boolean" coerce_boolean(value, field_def) when "date" coerce_date(value, field_def) when "datetime" coerce_datetime(value, field_def) when "enum" coerce_enum(value, field_def) when "json" coerce_json(value, field_def) else value.to_s end end |