lib/virtus/coercion/string.rb in virtus-0.0.10 vs lib/virtus/coercion/string.rb in virtus-0.1.0
- old
+ new
@@ -3,15 +3,18 @@
# Coerce String values
class String < Object
primitive ::String
- TRUE_VALUES = %w[ 1 t true ].freeze
- FALSE_VALUES = %w[ 0 f false ].freeze
+ 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
- NUMERIC_REGEXP = /\A(-?(?:0|[1-9]\d*)(?:\.\d+)?|(?:\.\d+))\z/.freeze
+ INTEGER_REGEXP = /[-+]?(?:0|[1-9]\d*)/.freeze
+ EXPONENT_REGEXP = /(?:[eE][-+]?\d+)/.freeze
+ FRACTIONAL_REGEXP = /(?:\.\d+#{EXPONENT_REGEXP}?)/.freeze
+ NUMERIC_REGEXP = /\A(#{INTEGER_REGEXP}#{FRACTIONAL_REGEXP}?|#{FRACTIONAL_REGEXP})\z/.freeze
# Coerce give value to a constant
#
# @example
# Virtus::Coercion::String.to_constant('String') # => String
@@ -94,10 +97,13 @@
#
# @return [Integer]
#
# @api public
def self.to_integer(value)
- to_numeric(value, :to_i)
+ # coerce to a Float first to evaluate scientific notation (if any)
+ # that may change the integer part, then convert to an integer
+ coerced = to_float(value)
+ ::Float === coerced ? coerced.to_i : coerced
end
# Coerce value to float
#
# @example