Module: ActiveRecord::AttributeMethods::BeforeTypeCast

Extended by:
ActiveSupport::Concern
Defined in:
activerecord/lib/active_record/attribute_methods/before_type_cast.rb

Overview

Active Record Attribute Methods Before Type Cast

ActiveRecord::AttributeMethods::BeforeTypeCast provides a way to read the value of the attributes before typecasting and deserialization.

class Task < ActiveRecord::Base
end

task = Task.new(id: '1', completed_on: '2012-10-21')
task.id           # => 1
task.completed_on # => Sun, 21 Oct 2012

task.attributes_before_type_cast
# => {"id"=>"1", "completed_on"=>"2012-10-21", ... }
task.read_attribute_before_type_cast('id')           # => "1"
task.read_attribute_before_type_cast('completed_on') # => "2012-10-21"

In addition to #read_attribute_before_type_cast and #attributes_before_type_cast, it declares a method for all attributes with the *_before_type_cast suffix.

task.id_before_type_cast           # => "1"
task.completed_on_before_type_cast # => "2012-10-21"

Instance Method Summary collapse

Methods included from ActiveSupport::Concern

append_features, class_methods, extended, included

Instance Method Details

#attributes_before_type_castObject

Returns a hash of attributes before typecasting and deserialization.

class Task < ActiveRecord::Base
end

task = Task.new(title: nil, is_done: true, completed_on: '2012-10-21')
task.attributes
# => {"id"=>nil, "title"=>nil, "is_done"=>true, "completed_on"=>Sun, 21 Oct 2012, "created_at"=>nil, "updated_at"=>nil}
task.attributes_before_type_cast
# => {"id"=>nil, "title"=>nil, "is_done"=>true, "completed_on"=>"2012-10-21", "created_at"=>nil, "updated_at"=>nil}


63
64
65
66
# File 'activerecord/lib/active_record/attribute_methods/before_type_cast.rb', line 63

def attributes_before_type_cast
  sync_with_transaction_state if @transaction_state&.finalized?
  @attributes.values_before_type_cast
end

#read_attribute_before_type_cast(attr_name) ⇒ Object

Returns the value of the attribute identified by attr_name before typecasting and deserialization.

class Task < ActiveRecord::Base
end

task = Task.new(id: '1', completed_on: '2012-10-21')
task.read_attribute('id')                            # => 1
task.read_attribute_before_type_cast('id')           # => '1'
task.read_attribute('completed_on')                  # => Sun, 21 Oct 2012
task.read_attribute_before_type_cast('completed_on') # => "2012-10-21"
task.read_attribute_before_type_cast(:completed_on)  # => "2012-10-21"


48
49
50
51
# File 'activerecord/lib/active_record/attribute_methods/before_type_cast.rb', line 48

def read_attribute_before_type_cast(attr_name)
  sync_with_transaction_state if @transaction_state&.finalized?
  @attributes[attr_name.to_s].value_before_type_cast
end