Module: SmoothOperator::TypeConverter
- Extended by:
- TypeConverter
- Included in:
- TypeConverter
- Defined in:
- lib/smooth_operator/type_converter.rb
Instance Method Summary collapse
- #convert(value, type) ⇒ Object
- #to_boolean(string) ⇒ Object
- #to_date(string) ⇒ Object
- #to_datetime(string) ⇒ Object
- #to_float(string) ⇒ Object
- #to_int(string) ⇒ Object
Instance Method Details
#convert(value, type) ⇒ Object
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
# File 'lib/smooth_operator/type_converter.rb', line 7 def convert(value, type) case type when :string, :text, String value.to_s when :int, :integer, Integer, Fixnum to_int(value) when :date, Date to_date(value) when :float, Float to_float(value) when :bool, :boolean to_boolean(value) when :datetime, :date_time, DateTime to_datetime(value) else Helpers.duplicate(value) end end |
#to_boolean(string) ⇒ Object
51 52 53 54 55 |
# File 'lib/smooth_operator/type_converter.rb', line 51 def to_boolean(string) value = string.to_s.downcase ['1', 'true'].include?(value) ? true : ['0', 'false'].include?(value) ? false : nil end |
#to_date(string) ⇒ Object
39 40 41 42 43 |
# File 'lib/smooth_operator/type_converter.rb', line 39 def to_date(string) return string if string.is_a?(Date) Date.parse(string) rescue nil end |
#to_datetime(string) ⇒ Object
45 46 47 48 49 |
# File 'lib/smooth_operator/type_converter.rb', line 45 def to_datetime(string) return string if string.is_a?(DateTime) DateTime.parse(string) rescue nil end |
#to_float(string) ⇒ Object
57 58 59 60 61 62 63 64 65 |
# File 'lib/smooth_operator/type_converter.rb', line 57 def to_float(string) return string if string.is_a?(Float) return 0 if string.nil? || !string.is_a?(String) value = string.scan(/-*\d+[,.]*\d*/).flatten.map(&:to_f).first value.nil? ? 0 : value end |
#to_int(string) ⇒ Object
33 34 35 36 37 |
# File 'lib/smooth_operator/type_converter.rb', line 33 def to_int(string) return string if string.is_a?(Fixnum) to_float(string).to_i end |