Class: SafeType::Converter
- Inherits:
-
Object
- Object
- SafeType::Converter
- Defined in:
- lib/safe_type.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
- @@METHODS =
[:to_true, :to_false, :to_int, :to_float, :to_date, :to_date_time, :to_time].freeze
Class Method Summary collapse
- .to_bool(input) ⇒ Object
- .to_date(input) ⇒ Object
- .to_date_time(input) ⇒ Object
- .to_false(input) ⇒ Object
- .to_float(input) ⇒ Object
- .to_int(input) ⇒ Object
- .to_time(input) ⇒ Object
- .to_true(input) ⇒ Object
- .to_type(input, type) ⇒ Object
Class Method Details
.to_bool(input) ⇒ Object
30 31 32 33 |
# File 'lib/safe_type.rb', line 30 def self.to_bool(input) return true unless self.to_true(input).nil? return false unless self.to_false(input).nil? end |
.to_date(input) ⇒ Object
43 44 45 46 |
# File 'lib/safe_type.rb', line 43 def self.to_date(input) return input unless input.respond_to?(:to_str) Date.parse(input) end |
.to_date_time(input) ⇒ Object
48 49 50 51 |
# File 'lib/safe_type.rb', line 48 def self.to_date_time(input) return input unless input.respond_to?(:to_str) DateTime.parse(input) end |
.to_false(input) ⇒ Object
26 27 28 |
# File 'lib/safe_type.rb', line 26 def self.to_false(input) false if @@FALSE_VALUES.include?(input.to_s) end |
.to_float(input) ⇒ Object
39 40 41 |
# File 'lib/safe_type.rb', line 39 def self.to_float(input) Float(input) end |
.to_int(input) ⇒ Object
35 36 37 |
# File 'lib/safe_type.rb', line 35 def self.to_int(input) Integer(input, base=10) end |
.to_time(input) ⇒ Object
53 54 55 56 |
# File 'lib/safe_type.rb', line 53 def self.to_time(input) return input unless input.respond_to?(:to_str) Time.parse(input) end |
.to_true(input) ⇒ Object
22 23 24 |
# File 'lib/safe_type.rb', line 22 def self.to_true(input) true if @@TRUE_VALUES.include?(input.to_s) end |
.to_type(input, type) ⇒ Object
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
# File 'lib/safe_type.rb', line 58 def self.to_type(input, type) return input if input.is_a?(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 == Boolean 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 |