Class: SafeType::Converter

Inherits:
Object
  • Object
show all
Defined in:
lib/safe_type/converter.rb

Constant Summary collapse

@@TRUE_VALUES =
%w[on On ON t true True TRUE T y yes Yes YES Y].freeze
@@FALSE_VALUES =
%w[off Off OFF f false False FALSE F n no No NO N].freeze

Class Method Summary collapse

Class Method Details

.to_bool(input) ⇒ Object

Raises:

  • (TypeError)


17
18
19
20
21
# File 'lib/safe_type/converter.rb', line 17

def self.to_bool(input)
  return true unless self.to_true(input).nil?
  return false unless self.to_false(input).nil?
  raise TypeError
end

.to_date(input) ⇒ Object



31
32
33
# File 'lib/safe_type/converter.rb', line 31

def self.to_date(input)
  ::Date.parse(input)
end

.to_date_time(input) ⇒ Object



35
36
37
# File 'lib/safe_type/converter.rb', line 35

def self.to_date_time(input)
  ::DateTime.parse(input)
end

.to_false(input) ⇒ Object



13
14
15
# File 'lib/safe_type/converter.rb', line 13

def self.to_false(input)
  false if @@FALSE_VALUES.include?(input.to_s)
end

.to_float(input) ⇒ Object



27
28
29
# File 'lib/safe_type/converter.rb', line 27

def self.to_float(input)
  Float(input)
end

.to_int(input) ⇒ Object



23
24
25
# File 'lib/safe_type/converter.rb', line 23

def self.to_int(input)
  Integer(Float(input))
end

.to_time(input) ⇒ Object



39
40
41
# File 'lib/safe_type/converter.rb', line 39

def self.to_time(input)
  ::Time.parse(input)
end

.to_true(input) ⇒ Object



9
10
11
# File 'lib/safe_type/converter.rb', line 9

def self.to_true(input)
  true if @@TRUE_VALUES.include?(input.to_s)
end

.to_type(input, type) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/safe_type/converter.rb', line 43

def self.to_type(input, type)
  return input if input.is_a?(type)
  return input.safe_type if input.respond_to?(:safe_type)
  return input.to_s if type == ::String
  return input.to_sym if type == ::Symbol
  return self.to_true(input) if type == ::TrueClass
  return self.to_false(input) if type == ::FalseClass
  return self.to_bool(input) if type == SafeType::BooleanMixin
  return self.to_int(input) if type == ::Integer
  return self.to_float(input) if type == ::Float
  return self.to_date(input) if type == ::Date
  return self.to_date_time(input) if type == ::DateTime
  return self.to_time(input) if type == ::Time
  return type.try_convert(input) if type.respond_to?(:try_convert)
  return type.new(input) if type.respond_to?(:new)
end