module DatastaxRails::AttributeMethods::Read

Methods for reading and caching attribute values

Constants

ATTRIBUTE_TYPES_CACHED_BY_DEFAULT

Public Instance Methods

read_attribute(attr_name) click to toggle source

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

# 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

Private Instance Methods

attribute(attribute_name) click to toggle source
# File lib/datastax_rails/attribute_methods/read.rb, line 114
def attribute(attribute_name)
  read_attribute(attribute_name)
end