Module: ActiveRecord::AttributeMethods::Read

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

Defined Under Namespace

Modules: ClassMethods

Constant Summary collapse

ATTRIBUTE_TYPES_CACHED_BY_DEFAULT =
[:datetime, :timestamp, :time, :date]

Instance Method Summary collapse

Instance Method Details

#read_attribute(attr_name) ⇒ Object

Returns the value of the attribute identified by attr_name after it has been typecast (for example, “2004-12-12” in a data column is cast to a date object, like Date.new(2004, 12, 12)).



75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/active_record/attribute_methods/read.rb', line 75

def read_attribute(attr_name)
  # If it's cached, just return it
  # We use #[] first as a perf optimization for non-nil values. See https://gist.github.com/jonleighton/3552829.
  name = attr_name.to_s
  @attributes_cache[name] || @attributes_cache.fetch(name) {
    column = @columns_hash.fetch(name) {
      return @attributes.fetch(name) {
        if name == 'id' && self.class.primary_key != name
          read_attribute(self.class.primary_key)
        end
      }
    }

    value = @attributes.fetch(name) {
      return block_given? ? yield(name) : nil
    }

    if self.class.cache_attribute?(name)
      @attributes_cache[name] = column.type_cast(value)
    else
      column.type_cast value
    end
  }
end