Module: Dry::Types::Coercions::Form

Extended by:
Dry::Types::Coercions
Defined in:
lib/dry/types/coercions/form.rb

Constant Summary collapse

TRUE_VALUES =
%w[1 on On ON t true True TRUE T y yes Yes YES Y].freeze
FALSE_VALUES =
%w[0 off Off OFF f false False FALSE F n no No NO N].freeze
BOOLEAN_MAP =
::Hash[TRUE_VALUES.product([true]) + FALSE_VALUES.product([false])].freeze

Class Method Summary collapse

Methods included from Dry::Types::Coercions

empty_str?, to_date, to_date_time, to_nil, to_time

Class Method Details

.to_ary(input) ⇒ Array, Object

Parameters:

  • input (Array, String, Object)

Returns:



68
69
70
# File 'lib/dry/types/coercions/form.rb', line 68

def self.to_ary(input)
  empty_str?(input) ? [] : input
end

.to_decimal(input) ⇒ BigDecimal, ...

Parameters:

  • input (#to_d, Object)

Returns:

  • (BigDecimal, nil, Object)


56
57
58
59
60
61
62
63
64
# File 'lib/dry/types/coercions/form.rb', line 56

def self.to_decimal(input)
  result = to_float(input)

  if result.instance_of?(Float)
    input.to_d
  else
    result
  end
end

.to_false(input) ⇒ Boolean, Object

Parameters:

  • input (String, Object)

Returns:

  • (Boolean, Object)

See Also:



26
27
28
# File 'lib/dry/types/coercions/form.rb', line 26

def self.to_false(input)
  BOOLEAN_MAP.fetch(input.to_s, input)
end

.to_float(input) ⇒ Float, ...

Parameters:

  • input (#to_f, Object)

Returns:

  • (Float, nil, Object)


44
45
46
47
48
49
50
51
52
# File 'lib/dry/types/coercions/form.rb', line 44

def self.to_float(input)
  if empty_str?(input)
    nil
  else
    Float(input)
  end
rescue ArgumentError, TypeError
  input
end

.to_hash(input) ⇒ Hash, Object

Parameters:

  • input (Hash, String, Object)

Returns:



74
75
76
# File 'lib/dry/types/coercions/form.rb', line 74

def self.to_hash(input)
  empty_str?(input) ? {} : input
end

.to_int(input) ⇒ Integer, ...

Parameters:

  • input (#to_int, #to_i, Object)

Returns:

  • (Integer, nil, Object)


32
33
34
35
36
37
38
39
40
# File 'lib/dry/types/coercions/form.rb', line 32

def self.to_int(input)
  if empty_str?(input)
    nil
  else
    Integer(input)
  end
rescue ArgumentError, TypeError
  input
end

.to_true(input) ⇒ Boolean, Object

Parameters:

  • input (String, Object)

Returns:

  • (Boolean, Object)

See Also:



18
19
20
# File 'lib/dry/types/coercions/form.rb', line 18

def self.to_true(input)
  BOOLEAN_MAP.fetch(input.to_s, input)
end