Module: DatastaxRails::AttributeMethods::Read

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

Overview

Methods for reading and caching attribute values

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)).



81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/datastax_rails/attribute_methods/read.rb', line 81

def read_attribute(attr_name)
  name = attr_name.to_s

  # If it's a lazily loaded attribute and hasn't been loaded yet, we need to do that now.
  if !loaded_attributes[name] && persisted? && !key.blank?
    @attributes[name.to_s] = self.class.select(name).with_cassandra.find(id).read_attribute(name)
    loaded_attributes[name] = true
  end

  # 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.
  @attributes_cache[name] || @attributes_cache.fetch(name) do
    column = @column_types_override[name] if @column_types_override
    column ||= self.class.attribute_definitions[name]

    return @attributes.fetch(name) do
      if name == 'id' && self.class.primary_key != name
        read_attribute(self.class.primary_key)
      end
    end unless column

    value = @attributes.fetch(name) { nil }

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