Skip to content

Commit

Permalink
Fold AM::Type::BigInteger#serialize implementation into Integer
Browse files Browse the repository at this point in the history
  • Loading branch information
nvasilevski committed Dec 19, 2024
1 parent cfc6c56 commit b506dd1
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 28 deletions.
25 changes: 4 additions & 21 deletions activemodel/lib/active_model/type/big_integer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,32 +23,15 @@ module Type
# All casting and serialization are performed in the same way as the
# standard ActiveModel::Type::Integer type.
class BigInteger < Integer
def serialize(value) # :nodoc:
case value
when ::Integer
# noop
when ::String
int = value.to_i
if int.zero? && value != "0"
return if non_numeric_string?(value)
end
value = int
else
value = super
end

value
end

def serialize_cast_value(value) # :nodoc:
value
end

def serializable?(value, &_)
true
end

private
def ensure_within_range!(value)
# noop
end

def max_value
::Float::INFINITY
end
Expand Down
16 changes: 9 additions & 7 deletions activemodel/lib/active_model/type/integer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -77,18 +77,13 @@ def serialize(value)
value = super
end

if out_of_range?(value)
raise ActiveModel::RangeError, "#{value} is out of range for #{self.class} with limit #{_limit} bytes"
end
ensure_within_range!(value)

value
end

def serialize_cast_value(value) # :nodoc:
if out_of_range?(value)
raise ActiveModel::RangeError, "#{value} is out of range for #{self.class} with limit #{_limit} bytes"
end

ensure_within_range!(value)
value
end

Expand All @@ -100,6 +95,13 @@ def serializable?(value)
end

private

def ensure_within_range!(value)
return unless out_of_range?(value)

raise ActiveModel::RangeError, "#{value} is out of range for #{self.class} with limit #{_limit} bytes"
end

def out_of_range?(value)
value && (@max <= value || @min > value)
end
Expand Down
17 changes: 17 additions & 0 deletions bench_big_int.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
require 'benchmark/ips'
require 'active_model'

class TestModel
include ActiveModel::Model
include ActiveModel::Attributes

attribute :number, :big_integer
end

Benchmark.ips do |x|
model = TestModel.new
x.load! 'tmp/bigint_conversion_benchmark'

x.report("big_integer") { model.number = BigDecimal("9223372036854775807") }
x.save! 'tmp/bigint_conversion_benchmark'
end

0 comments on commit b506dd1

Please sign in to comment.