lib/lotus/utils/kernel.rb in lotus-utils-0.3.2 vs lib/lotus/utils/kernel.rb in lotus-utils-0.3.3
- old
+ new
@@ -15,10 +15,18 @@
module Lotus
module Utils
# Kernel utilities
# @since 0.1.1
module Kernel
+ # Matcher for numeric values
+ #
+ # @since 0.3.3
+ # @api private
+ #
+ # @see Lotus::Utils::Kernel.Integer
+ NUMERIC_MATCHER = /\A([\d\/\.\+iE]+|NaN|Infinity)\z/.freeze
+
# Coerces the argument to be an Array.
#
# It's similar to Ruby's Kernel.Array, but it applies further
# transformations:
#
@@ -283,10 +291,14 @@
#
# # Missing #to_int and #to_i
# input = OpenStruct.new(color: 'purple')
# Lotus::Utils::Kernel.Integer(input) # => TypeError
#
+ # # String that doesn't represent an integer
+ # input = 'hello'
+ # Lotus::Utils::Kernel.Integer(input) # => TypeError
+ #
# # When true
# input = true
# Lotus::Utils::Kernel.Integer(input) # => TypeError
#
# # When false
@@ -318,11 +330,12 @@
# Lotus::Utils::Kernel.Integer(input) # => TypeError
def self.Integer(arg)
super(arg)
rescue ArgumentError, TypeError, NoMethodError
begin
- if arg.respond_to?(:to_i)
+ case arg
+ when NilClass, ->(a) { a.respond_to?(:to_i) && a.to_s.match(NUMERIC_MATCHER) }
arg.to_i
else
raise TypeError.new "can't convert into Integer"
end
rescue NoMethodError
@@ -396,20 +409,26 @@
#
# # When Time
# input = Time.now
# Lotus::Utils::Kernel.BigDecimal(input) # => TypeError
#
+ # # String that doesn't represent a big decimal
+ # input = 'hello'
+ # Lotus::Utils::Kernel.BigDecimal(input) # => TypeError
+ #
# # Missing #respond_to?
# input = BasicObject.new
# Lotus::Utils::Kernel.BigDecimal(input) # => TypeError
def self.BigDecimal(arg)
case arg
when ->(a) { a.respond_to?(:to_d) } then arg.to_d
when Float, Complex, Rational
BigDecimal(arg.to_s)
- else
+ when ->(a) { a.to_s.match(NUMERIC_MATCHER) }
BigDecimal.new(arg)
+ else
+ raise TypeError.new "can't convert into BigDecimal"
end
rescue NoMethodError
raise TypeError.new "can't convert into BigDecimal"
end
@@ -512,10 +531,14 @@
#
# # Missing #nil?
# input = BasicObject.new
# Lotus::Utils::Kernel.Float(input) # => TypeError
#
+ # # String that doesn't represent a float
+ # input = 'hello'
+ # Lotus::Utils::Kernel.Float(input) # => TypeError
+ #
# # big rational
# input = Rational(-8) ** Rational(1, 3)
# Lotus::Utils::Kernel.Float(input) # => TypeError
#
# # big complex represented as a string
@@ -523,10 +546,11 @@
# Lotus::Utils::Kernel.Float(input) # => TypeError
def self.Float(arg)
super(arg)
rescue ArgumentError, TypeError
begin
- if arg.respond_to?(:to_f)
+ case arg
+ when NilClass, ->(a) { a.respond_to?(:to_f) && a.to_s.match(NUMERIC_MATCHER) }
arg.to_f
else
raise TypeError.new "can't convert into Float"
end
rescue NoMethodError