read.rb 3.6 KB
Newer Older
J
Joshua Peek 已提交
1
module ActiveRecord
J
Jon Leighton 已提交
2 3 4 5
  ActiveSupport.on_load(:active_record_config) do
    mattr_accessor :attribute_types_cached_by_default, instance_accessor: false
  end

J
Joshua Peek 已提交
6 7 8 9
  module AttributeMethods
    module Read
      extend ActiveSupport::Concern

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

12
      included do
J
Jon Leighton 已提交
13
        config_attribute :attribute_types_cached_by_default
14
      end
J
Joshua Peek 已提交
15 16

      module ClassMethods
17 18 19 20
        # +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+).
        def cache_attributes(*attribute_names)
21
          cached_attributes.merge attribute_names.map { |attr| attr.to_s }
22 23 24 25 26
        end

        # Returns the attributes which are cached. By default time related columns
        # with datatype <tt>:datetime, :timestamp, :time, :date</tt> are cached.
        def cached_attributes
J
Jeremy Kemper 已提交
27
          @cached_attributes ||= columns.select { |c| cacheable_column?(c) }.map { |col| col.name }.to_set
28 29 30 31 32 33 34
        end

        # Returns +true+ if the provided attribute is being cached.
        def cache_attribute?(attr_name)
          cached_attributes.include?(attr_name)
        end

J
Joshua Peek 已提交
35
        protected
36

37 38 39 40 41 42 43 44 45 46 47
        # We want to generate the methods via module_eval rather than define_method,
        # because define_method is slower on dispatch and uses more memory (because it
        # creates a closure).
        #
        # But sometimes the database might return columns with characters that are not
        # allowed in normal method names (like 'my_column(omg)'. So to work around this
        # we first define with the __temp__ identifier, and then use alias method to
        # rename it to what we want.
        def define_method_attribute(attr_name)
          generated_attribute_methods.module_eval <<-STR, __FILE__, __LINE__ + 1
            def __temp__
48
              read_attribute('#{attr_name}') { |n| missing_attribute(n, caller) }
49 50 51 52 53
            end
            alias_method '#{attr_name}', :__temp__
            undef_method :__temp__
          STR
        end
J
Joshua Peek 已提交
54

55
        private
56

57
        def cacheable_column?(column)
58 59 60 61 62
          if attribute_types_cached_by_default == ATTRIBUTE_TYPES_CACHED_BY_DEFAULT
            ! serialized_attributes.include? column.name
          else
            attribute_types_cached_by_default.include?(column.type)
          end
63
        end
J
Joshua Peek 已提交
64
      end
65 66

      ActiveRecord::Model.attribute_types_cached_by_default = ATTRIBUTE_TYPES_CACHED_BY_DEFAULT
J
Joshua Peek 已提交
67 68 69 70

      # Returns the value of the attribute identified by <tt>attr_name</tt> 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)).
      def read_attribute(attr_name)
71
        # If it's cached, just return it
72
        @attributes_cache.fetch(attr_name.to_s) { |name|
73
          column = @columns_hash.fetch(name) {
74
            return @attributes.fetch(name) {
75 76
              if name == 'id' && self.class.primary_key != name
                read_attribute(self.class.primary_key)
77
              end
78
            }
79
          }
80

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

85 86
          if self.class.cache_attribute?(name)
            @attributes_cache[name] = column.type_cast(value)
87 88 89 90
          else
            column.type_cast value
          end
        }
J
Jon Leighton 已提交
91 92
      end

93
      private
94

95 96 97
      def attribute(attribute_name)
        read_attribute(attribute_name)
      end
J
Joshua Peek 已提交
98 99 100
    end
  end
end