class ActiveModel::Type::Integer
end
attribute :age, :integer, limit: 6
include ActiveModel::Attributes
class Person
an attribute:
raised. The default limit is 4 bytes, and can be customized when declaring
limited number of bytes. If it cannot, an ActiveModel::RangeError will be
Serialization also validates that the integer can be stored using a
serialized as nil
, for example.
Serialization also works under the same principle. Non-numeric strings are
person.age # => nil (because Symbol does not define #to_i)
person.age = :not_an_integer
person.age # => nil
person.age = “”
person.age # => 18
person.age = “18”
person = Person.new
the value will be cast to nil
.
are cast to nil
. If a to_i
method is not defined or raises an error,
Values are cast using their to_i
method, except for blank strings, which
end
attribute :age, :integer
include ActiveModel::Attributes
class Person
the :integer
key.
Attribute type for integer representation. This type is registered under
= Active Model Integer Type
def _limit
def _limit limit || DEFAULT_LIMIT end
def cast_value(value)
def cast_value(value) value.to_i rescue nil end
def deserialize(value)
def deserialize(value) return if value.blank? value.to_i end
def ensure_in_range(value)
def ensure_in_range(value) unless in_range?(value) raise ActiveModel::RangeError, "#{value} is out of range for #{self.class} with limit #{_limit} bytes" end value end
def in_range?(value)
def in_range?(value) !value || range.member?(value) end
def initialize(**)
def initialize(**) super @range = min_value...max_value end
def max_value
def max_value 1 << (_limit * 8 - 1) # 8 bits per byte with one bit for sign end
def min_value
def min_value -max_value end
def serializable?(value)
def serializable?(value) cast_value = cast(value) in_range?(cast_value) || begin yield cast_value if block_given? false end end
def serialize(value)
def serialize(value) return if value.is_a?(::String) && non_numeric_string?(value) ensure_in_range(super) end
def serialize_cast_value(value) # :nodoc:
def serialize_cast_value(value) # :nodoc: ensure_in_range(value) end
def type
def type :integer end