Module: ActiveRecord::AttributeMethods::Read::ClassMethods

Defined in:
lib/active_record/attribute_methods/read.rb

Instance Method Summary collapse

Instance Method Details

#cache_attribute?(attr_name) ⇒ Boolean

Returns true if the provided attribute is being cached.

Returns:

  • (Boolean)


28
29
30
# File 'lib/active_record/attribute_methods/read.rb', line 28

def cache_attribute?(attr_name)
  cached_attributes.include?(attr_name)
end

#cache_attributes(*attribute_names) ⇒ Object

cache_attributes allows you to declare which converted attribute values should be cached. Usually caching only pays off for attributes with expensive conversion methods, like time related columns (e.g. created_at, updated_at).



17
18
19
# File 'lib/active_record/attribute_methods/read.rb', line 17

def cache_attributes(*attribute_names)
  cached_attributes.merge attribute_names.map { |attr| attr.to_s }
end

#cached_attributesObject

Returns the attributes which are cached. By default time related columns with datatype :datetime, :timestamp, :time, :date are cached.



23
24
25
# File 'lib/active_record/attribute_methods/read.rb', line 23

def cached_attributes
  @cached_attributes ||= columns.select { |c| cacheable_column?(c) }.map { |col| col.name }.to_set
end

#type_cast_attribute(attr_name, attributes, cache = {}) ⇒ Object

:nodoc:



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/active_record/attribute_methods/read.rb', line 40

def type_cast_attribute(attr_name, attributes, cache = {}) #:nodoc:
  return unless attr_name
  attr_name = attr_name.to_s

  if generated_external_attribute_methods.method_defined?(attr_name)
    if attributes.has_key?(attr_name) || attr_name == 'id'
      generated_external_attribute_methods.send(attr_name, attributes[attr_name], attributes, cache, attr_name)
    end
  elsif !attribute_methods_generated?
    # If we haven't generated the caster methods yet, do that and
    # then try again
    define_attribute_methods
    type_cast_attribute(attr_name, attributes, cache)
  else
    # If we get here, the attribute has no associated DB column, so
    # just return it verbatim.
    attributes[attr_name]
  end
end

#undefine_attribute_methodsObject



32
33
34
35
36
37
38
# File 'lib/active_record/attribute_methods/read.rb', line 32

def undefine_attribute_methods
  generated_external_attribute_methods.module_eval do
    instance_methods.each { |m| undef_method(m) }
  end

  super
end