read.rb 3.8 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+).
21
        def cache_attributes(*attribute_names)
22
          cached_attributes.merge attribute_names.map { |attr| attr.to_s }
23 24 25 26 27
        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 已提交
28
          @cached_attributes ||= columns.select { |c| cacheable_column?(c) }.map { |col| col.name }.to_set
29 30 31 32 33 34 35
        end

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

J
Joshua Peek 已提交
36
        protected
37

38 39 40 41 42 43 44 45 46 47 48
        # 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__
49
              read_attribute(:'#{attr_name}') { |n| missing_attribute(n, caller) }
50 51 52 53 54
            end
            alias_method '#{attr_name}', :__temp__
            undef_method :__temp__
          STR
        end
J
Joshua Peek 已提交
55

56
        private
57

58
        def cacheable_column?(column)
59 60 61 62 63
          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
64
        end
J
Joshua Peek 已提交
65
      end
66 67

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

69 70 71
      # 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)).
J
Joshua Peek 已提交
72
      def read_attribute(attr_name)
73 74 75
        return unless attr_name
        name_sym = attr_name.to_sym

76
        # If it's cached, just return it
J
Jon Leighton 已提交
77 78
        # We use #[] first as a perf optimization for non-nil values. See https://gist.github.com/3552829.
        @attributes_cache[name_sym] || @attributes_cache.fetch(name_sym) {
79 80
          name = attr_name.to_s

81
          column = @columns_hash.fetch(name) {
82
            return @attributes.fetch(name) {
83
              if name_sym == :id && self.class.primary_key != name
84
                read_attribute(self.class.primary_key)
85
              end
86
            }
87
          }
88

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

93
          if self.class.cache_attribute?(name)
94
            @attributes_cache[name_sym] = column.type_cast(value)
95 96 97 98
          else
            column.type_cast value
          end
        }
J
Jon Leighton 已提交
99 100
      end

101
      private
102

103 104 105
      def attribute(attribute_name)
        read_attribute(attribute_name)
      end
J
Joshua Peek 已提交
106 107 108
    end
  end
end