Module: I18nYamlEditor::Cast

Included in:
Update
Defined in:
lib/i18n_yaml_editor/cast.rb

Overview

Transformation provides

Constant Summary collapse

TYPES =

Lists all supported types of conversions

%i[numeric boolean array].freeze
CHECK =

Contains a check method for each supported type

{
  numeric: ->(klass) { klass < Numeric },
  boolean: ->(klass) { [TrueClass, FalseClass].include?(klass) },
  array: ->(klass) { klass == Array }
}.freeze
CONVERT =

Contains a conversion method for each supported type

{
  numeric: lambda do |value|
             num = BigDecimal(value)
             num.frac.zero? ? num.to_i : num.to_f
           end,
  boolean: ->(value) { value.casecmp('true').zero? },
  array: ->(value) { value.split("\r\n") }
}.freeze

Instance Method Summary collapse

Instance Method Details

#cast(klass, value) ⇒ Object

Converts a given value to a specific data type



27
28
29
30
31
32
# File 'lib/i18n_yaml_editor/cast.rb', line 27

def cast(klass, value)
  TYPES.each do |type|
    return CONVERT[type].call(value) if CHECK[type].call(klass)
  end
  value.to_s # String, blank
end