Skip to content

Commit

Permalink
Merge pull request #127 from greyblake/126_e_notation_coercion
Browse files Browse the repository at this point in the history
Fix E notation coercion
  • Loading branch information
dkubb committed Nov 30, 2012
2 parents e2f0016 + 0b753a8 commit ef4fbe4
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 2 deletions.
8 changes: 6 additions & 2 deletions lib/virtus/coercion/string.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,12 @@ class String < Object

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
FRACTIONAL_REGEXP = /(?:\.\d+)/.freeze

NUMERIC_REGEXP = /\A(
#{INTEGER_REGEXP}#{FRACTIONAL_REGEXP}?#{EXPONENT_REGEXP}? |
#{FRACTIONAL_REGEXP}#{EXPONENT_REGEXP}?
)\z/x.freeze

# Coerce give value to a constant
#
Expand Down
12 changes: 12 additions & 0 deletions spec/unit/virtus/coercion/string/class_methods/to_float_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@
'.1e-1' => 0.01,
'.1E+1' => 1.0,
'.1E-1' => 0.01,
'1e1' => 10.0,
'1E+1' => 10.0,
'+1e-1' => 0.1,
'-1E1' => -10.0,
'-1e-1' => -0.1,
}.each do |value, expected|
context "with #{value.inspect}" do
let(:string) { value }
Expand All @@ -42,4 +47,11 @@

it { should equal(string) }
end

context 'string starts with e' do
let(:string) { 'e1' }

# In further version it will raise exception
it { should == 'e1' }
end
end
12 changes: 12 additions & 0 deletions spec/unit/virtus/coercion/string/class_methods/to_integer_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@
'.1e-1' => 0,
'.1E+1' => 1,
'.1E-1' => 0,
'1e1' => 10,
'1E+1' => 10,
'+1e-1' => 0,
'-1E1' => -10,
'-1e-1' => 0,
min_float.to_s => min_float.to_i,
max_float.to_s => max_float.to_i,
}.each do |value, expected|
Expand All @@ -53,4 +58,11 @@

it { should == 334490140000101135 }
end

context 'string starts with e' do
let(:string) { 'e1' }

# In further version it will raise exception
it { should == 'e1' }
end
end

0 comments on commit ef4fbe4

Please sign in to comment.