Skip to content

Commit

Permalink
let all Numeric types accept implicit Integers
Browse files Browse the repository at this point in the history
  • Loading branch information
AaronLasseigne committed Jun 8, 2017
1 parent 3684cf8 commit 040bae2
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 12 deletions.
7 changes: 4 additions & 3 deletions lib/active_interaction/filters/abstract_numeric_filter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,12 @@ class AbstractNumericFilter < AbstractFilter
private :_cast

def cast(value, context)
case value
when klass
if value.is_a?(klass)
value
when Numeric, String
elsif value.is_a?(Numeric) || value.is_a?(String)
convert(value, context)
elsif value.respond_to?(:to_int)
convert(value.to_int, context)
else
super
end
Expand Down
8 changes: 0 additions & 8 deletions lib/active_interaction/filters/integer_filter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,6 @@ class Base
class IntegerFilter < AbstractNumericFilter
register :integer

def cast(value, *)
if value.respond_to?(:to_int)
value.to_int
else
super
end
end

private

# @return [Integer]
Expand Down
14 changes: 14 additions & 0 deletions spec/active_interaction/filters/decimal_filter_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,20 @@
end
end

context 'with an implicit Integer' do
let(:value) do
Class.new do
def to_int
@to_int ||= rand(1 << 16)
end
end.new
end

it 'returns a BigDecimal' do
expect(result).to eql BigDecimal.new(value.to_int)
end
end

context 'with a Numeric' do
let(:value) { rand(1 << 16) }

Expand Down
17 changes: 16 additions & 1 deletion spec/active_interaction/filters/float_filter_spec.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# coding: utf-8

require 'bigdecimal'
require 'spec_helper'

describe ActiveInteraction::FloatFilter, :filter do
Expand All @@ -17,8 +18,22 @@
end
end

context 'with an implicit Integer' do
let(:value) do
Class.new do
def to_int
@to_int ||= rand(1 << 16)
end
end.new
end

it 'returns a Float' do
expect(result).to eql value.to_int.to_f
end
end

context 'with a Numeric' do
let(:value) { rand(1 << 16) }
let(:value) { BigDecimal.new('1.2') }

it 'returns a Float' do
expect(result).to eql value.to_f
Expand Down

0 comments on commit 040bae2

Please sign in to comment.