Module: SimpleMapper::Attributes::Types::Float
- Defined in:
- lib/simple_mapper/attributes/types.rb
Overview
Provides basic support for floating point numbers, closely tied to the core Ruby :Float:.
Registered as type :float
This is intended to be reasonably flexible and work with inputs that look numeric whether or not they literally appear to be “floats”.
Constant Summary collapse
- PATTERN =
/^([0-9]+)(?:(\.)([0-9]*))?$/
Class Method Summary collapse
-
.decode(value) ⇒ Object
Decode a numeric-looking
value
(whether a string or otherwise) into aFloat
. -
.default ⇒ Object
Returns the type default value of
nil
. -
.encode(value) ⇒ Object
Encodes a float-like
value
as a string, conforming to the basic syntax used fordecode
.
Class Method Details
.decode(value) ⇒ Object
Decode a numeric-looking value
(whether a string or otherwise) into a Float
.
String inputs for value
should be numeric and may or may not have a decimal point, with or without digits following the decimal point. Therefore, the following values would all decode nicely:
* +"14"+ to +14.0+
* +"0"+ to +0.0+
* +"123."+ to +123.0+
* +"100.22022"+ to +100.22022+
* +"0.0001"+ to +0.0001+
* +14+ to +14.0+
* +0+ to +0.0+
The empty string will result in a value of nil
27 28 29 30 31 32 33 34 35 |
# File 'lib/simple_mapper/attributes/types.rb', line 27 def self.decode(value) return nil if (str = value.to_s).length == 0 return value if Float === value match = str.match(PATTERN) raise(SimpleMapper::TypeConversionException, "Cannot decode '#{value}' to Float.") unless match value = match[1] value += match[2] + match[3] if match[3].to_s.length > 0 value.to_s.to_f end |
.default ⇒ Object
Returns the type default value of nil
.
48 49 50 |
# File 'lib/simple_mapper/attributes/types.rb', line 48 def self.default nil end |
.encode(value) ⇒ Object
Encodes a float-like value
as a string, conforming to the basic syntax used for decode
.
39 40 41 42 43 44 45 |
# File 'lib/simple_mapper/attributes/types.rb', line 39 def self.encode(value) return nil if value.nil? if ! value.respond_to?(:to_f) or value.respond_to?(:match) && ! value.match(PATTERN) raise(SimpleMapper::TypeConversionException, "Cannot encode '#{value}' as Float.") end value.to_f.to_s end |