Module: Dry::Data::Coercions::Form

Defined in:
lib/dry/data/coercions/form.rb

Constant Summary collapse

TRUE_VALUES =
%w[1 on  t true  y yes].freeze
FALSE_VALUES =
%w[0 off f false n no].freeze
BOOLEAN_MAP =
Hash[TRUE_VALUES.product([true]) + FALSE_VALUES.product([false])].freeze

Class Method Summary collapse

Class Method Details

.to_date(input) ⇒ Object



21
22
23
24
25
# File 'lib/dry/data/coercions/form.rb', line 21

def self.to_date(input)
  Date.parse(input)
rescue ArgumentError
  input
end

.to_date_time(input) ⇒ Object



27
28
29
30
31
# File 'lib/dry/data/coercions/form.rb', line 27

def self.to_date_time(input)
  DateTime.parse(input)
rescue ArgumentError
  input
end

.to_decimal(input) ⇒ Object



75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/dry/data/coercions/form.rb', line 75

def self.to_decimal(input)
  if input == ''
    nil
  else
    result = to_float(input)

    if result.is_a?(Float)
      result.to_d
    else
      result
    end
  end
end

.to_false(input) ⇒ Object



43
44
45
# File 'lib/dry/data/coercions/form.rb', line 43

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

.to_float(input) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/dry/data/coercions/form.rb', line 61

def self.to_float(input)
  if input == ''
    nil
  else
    result = input.to_f

    if result == 0.0 && (input != '0' || input != '0.0')
      input
    else
      result
    end
  end
end

.to_int(input) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/dry/data/coercions/form.rb', line 47

def self.to_int(input)
  if input == ''
    nil
  else
    result = input.to_i

    if result === 0 && input != '0'
      input
    else
      result
    end
  end
end

.to_nil(input) ⇒ Object



13
14
15
16
17
18
19
# File 'lib/dry/data/coercions/form.rb', line 13

def self.to_nil(input)
  if input.is_a?(String) && input == ''
    nil
  else
    input
  end
end

.to_time(input) ⇒ Object



33
34
35
36
37
# File 'lib/dry/data/coercions/form.rb', line 33

def self.to_time(input)
  Time.parse(input)
rescue ArgumentError
  input
end

.to_true(input) ⇒ Object



39
40
41
# File 'lib/dry/data/coercions/form.rb', line 39

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