Class: ActiveModel::Type::Integer

Inherits:
Value show all
Includes:
Helpers::Numeric
Defined in:
activemodel/lib/active_model/type/integer.rb

Overview

Attribute type for integer representation. This type is registered under the :integer key.

class Person
  include ActiveModel::Attributes

  attribute :age, :integer
end

person = Person.new
person.age = "18"

person.age # => 18

Values are cast using their to_i method, if it exists. If it does not exist, or if it raises an error, the value will be cast to nil:

person.age = :not_an_integer
person.age # => nil (because Symbol does not define #to_i)

Serialization also works under the same principle. Non-numeric strings are serialized as nil, for example.

Serialization also validates that the integer can be stored using a limited number of bytes. If it cannot, an ActiveModel::RangeError will be raised. The default limit is 4 bytes, and can be customized when declaring an attribute:

class Person
  include ActiveModel::Attributes

  attribute :age, :integer, limit: 6
end

Constant Summary collapse

DEFAULT_LIMIT =

Column storage size in bytes. 4 bytes means an integer as opposed to smallint etc.

4

Instance Attribute Summary

Attributes inherited from Value

#limit, #precision, #scale

Instance Method Summary collapse

Methods included from Helpers::Numeric

#cast, #changed?

Methods inherited from Value

#==, #assert_valid_value, #binary?, #cast, #changed?, #changed_in_place?, #force_equality?, #hash, #map, #type_cast_for_schema, #value_constructed_by_mass_assignment?

Constructor Details

#initializeInteger

Returns a new instance of Integer.


45
46
47
48
# File 'activemodel/lib/active_model/type/integer.rb', line 45

def initialize(**)
  super
  @range = min_value...max_value
end

Instance Method Details

#deserialize(value) ⇒ Object


54
55
56
57
# File 'activemodel/lib/active_model/type/integer.rb', line 54

def deserialize(value)
  return if value.blank?
  value.to_i
end

#serializable?(value) ⇒ Boolean

Returns:


64
65
66
67
68
69
70
# File 'activemodel/lib/active_model/type/integer.rb', line 64

def serializable?(value)
  cast_value = cast(value)
  in_range?(cast_value) || begin
    yield cast_value if block_given?
    false
  end
end

#serialize(value) ⇒ Object


59
60
61
62
# File 'activemodel/lib/active_model/type/integer.rb', line 59

def serialize(value)
  return if value.is_a?(::String) && non_numeric_string?(value)
  ensure_in_range(super)
end

#typeObject


50
51
52
# File 'activemodel/lib/active_model/type/integer.rb', line 50

def type
  :integer
end