read.rb 5.1 KB
Newer Older
J
Joshua Peek 已提交
1 2 3 4 5
module ActiveRecord
  module AttributeMethods
    module Read
      extend ActiveSupport::Concern

6 7
      ATTRIBUTE_TYPES_CACHED_BY_DEFAULT = [:datetime, :timestamp, :time, :date]

J
Joshua Peek 已提交
8
      included do
9 10
        cattr_accessor :attribute_types_cached_by_default, :instance_writer => false
        self.attribute_types_cached_by_default = ATTRIBUTE_TYPES_CACHED_BY_DEFAULT
J
Joshua Peek 已提交
11
      end
J
Joshua Peek 已提交
12 13

      module ClassMethods
14 15 16 17
        # +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)
18
          cached_attributes.merge attribute_names.map { |attr| attr.to_s }
19 20 21 22 23
        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 已提交
24
          @cached_attributes ||= columns.select { |c| cacheable_column?(c) }.map { |col| col.name }.to_set
25 26 27 28 29 30 31
        end

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

32
        def undefine_attribute_methods
J
Jon Leighton 已提交
33 34 35 36 37
          if base_class == self
            generated_attribute_methods.module_eval do
              public_methods(false).each do |m|
                singleton_class.send(:undef_method, m) if m.to_s =~ /^attribute_/
              end
38 39 40 41 42 43
            end
          end

          super
        end

J
Joshua Peek 已提交
44
        protected
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).
48
          #
49 50 51 52
          # 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.
53
          def define_method_attribute(attr_name)
J
Jon Leighton 已提交
54 55 56
            cast_code = attribute_cast_code(attr_name)
            internal  = internal_attribute_access_code(attr_name, cast_code)
            external  = external_attribute_access_code(attr_name, cast_code)
57

58 59 60 61 62 63 64
            generated_attribute_methods.module_eval <<-STR, __FILE__, __LINE__
              def __temp__
                #{internal}
              end
              alias_method '#{attr_name}', :__temp__
              undef_method :__temp__
            STR
65

66 67 68
            generated_attribute_methods.singleton_class.module_eval <<-STR, __FILE__, __LINE__
              def __temp__(v, attributes, attributes_cache, attr_name)
                #{external}
69
              end
J
Jon Leighton 已提交
70
              alias_method 'attribute_#{attr_name}', :__temp__
71 72
              undef_method :__temp__
            STR
J
Joshua Peek 已提交
73 74 75
          end

        private
J
Jeremy Kemper 已提交
76
          def cacheable_column?(column)
77
            attribute_types_cached_by_default.include?(column.type)
78
          end
J
Joshua Peek 已提交
79

J
Jon Leighton 已提交
80
          def internal_attribute_access_code(attr_name, cast_code)
81
            access_code = "(v=@attributes[attr_name]) && #{cast_code}"
82

J
Jon Leighton 已提交
83
            unless attr_name == primary_key
84
              access_code.insert(0, "missing_attribute(attr_name, caller) unless @attributes.has_key?(attr_name); ")
J
Joshua Peek 已提交
85 86 87
            end

            if cache_attribute?(attr_name)
88
              access_code = "@attributes_cache[attr_name] ||= (#{access_code})"
J
Joshua Peek 已提交
89
            end
90

91
            "attr_name = '#{attr_name}'; #{access_code}"
92
          end
93

J
Jon Leighton 已提交
94 95
          def external_attribute_access_code(attr_name, cast_code)
            access_code = "v && #{cast_code}"
96 97 98 99 100 101 102 103

            if cache_attribute?(attr_name)
              access_code = "attributes_cache[attr_name] ||= (#{access_code})"
            end

            access_code
          end

104 105
          def attribute_cast_code(attr_name)
            columns_hash[attr_name].type_cast_code('v')
J
Joshua Peek 已提交
106 107 108 109 110 111
          end
      end

      # 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)
112
        attr_name = attr_name.to_s
J
Jon Leighton 已提交
113
        accessor  = "attribute_#{attr_name}"
114 115
        methods   = self.class.generated_attribute_methods

J
Jon Leighton 已提交
116
        if methods.respond_to?(accessor)
117
          if @attributes.has_key?(attr_name) || attr_name == 'id'
J
Jon Leighton 已提交
118
            methods.send(accessor, @attributes[attr_name], @attributes, @attributes_cache, attr_name)
119
          end
120 121 122 123 124
        elsif !self.class.attribute_methods_generated?
          # If we haven't generated the caster methods yet, do that and
          # then try again
          self.class.define_attribute_methods
          read_attribute(attr_name)
125
        else
126 127 128
          # If we get here, the attribute has no associated DB column, so
          # just return it verbatim.
          @attributes[attr_name]
J
Jon Leighton 已提交
129 130 131 132
        end
      end

      private
J
Joshua Peek 已提交
133 134 135
        def attribute(attribute_name)
          read_attribute(attribute_name)
        end
J
Joshua Peek 已提交
136 137 138
    end
  end
end