Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 197 lines (175 sloc) 7.444 kb
e8550ee @jeremy Cherry-pick core extensions
jeremy authored
1 require 'active_support/core_ext/enumerable'
2
2b3cc24 @jeremy r4854@ks: jeremy | 2006-07-30 00:59:18 -0700
jeremy authored
3 module ActiveRecord
4 module AttributeMethods #:nodoc:
4e50a35 @josh Break up DependencyModule's dual function of providing a "depend_on" DSL...
josh authored
5 extend ActiveSupport::Concern
a2875be @brynary Use DependencyModule for included hooks in ActiveRecord
brynary authored
6
4db718e @NZKoz Only cache attributes which need it for performance reasons. Closes #976...
NZKoz authored
7 ATTRIBUTE_TYPES_CACHED_BY_DEFAULT = [:datetime, :timestamp, :time, :date]
2b3cc24 @jeremy r4854@ks: jeremy | 2006-07-30 00:59:18 -0700
jeremy authored
8
a2875be @brynary Use DependencyModule for included hooks in ActiveRecord
brynary authored
9 included do
10 cattr_accessor :attribute_types_cached_by_default, :instance_writer => false
11 self.attribute_types_cached_by_default = ATTRIBUTE_TYPES_CACHED_BY_DEFAULT
2b3cc24 @jeremy r4854@ks: jeremy | 2006-07-30 00:59:18 -0700
jeremy authored
12 end
13
14 # Declare and check for suffixed attribute methods.
15 module ClassMethods
46f30f9 @lifo Merge documentation changes from docrails.
lifo authored
16 # Declares a method available for all attributes with the given suffix.
17 # Uses +method_missing+ and <tt>respond_to?</tt> to rewrite the method
18 #
2b3cc24 @jeremy r4854@ks: jeremy | 2006-07-30 00:59:18 -0700
jeremy authored
19 # #{attr}#{suffix}(*args, &block)
46f30f9 @lifo Merge documentation changes from docrails.
lifo authored
20 #
2b3cc24 @jeremy r4854@ks: jeremy | 2006-07-30 00:59:18 -0700
jeremy authored
21 # to
46f30f9 @lifo Merge documentation changes from docrails.
lifo authored
22 #
2b3cc24 @jeremy r4854@ks: jeremy | 2006-07-30 00:59:18 -0700
jeremy authored
23 # attribute#{suffix}(#{attr}, *args, &block)
24 #
46f30f9 @lifo Merge documentation changes from docrails.
lifo authored
25 # An <tt>attribute#{suffix}</tt> instance method must exist and accept at least
26 # the +attr+ argument.
2b3cc24 @jeremy r4854@ks: jeremy | 2006-07-30 00:59:18 -0700
jeremy authored
27 #
28 # For example:
46f30f9 @lifo Merge documentation changes from docrails.
lifo authored
29 #
2b3cc24 @jeremy r4854@ks: jeremy | 2006-07-30 00:59:18 -0700
jeremy authored
30 # class Person < ActiveRecord::Base
31 # attribute_method_suffix '_changed?'
32 #
33 # private
34 # def attribute_changed?(attr)
35 # ...
36 # end
37 # end
38 #
39 # person = Person.find(1)
40 # person.name_changed? # => false
41 # person.name = 'Hubert'
42 # person.name_changed? # => true
43 def attribute_method_suffix(*suffixes)
44 attribute_method_suffixes.concat suffixes
45 rebuild_attribute_method_regexp
46 end
47
48 # Returns MatchData if method_name is an attribute method.
49 def match_attribute_method?(method_name)
50 rebuild_attribute_method_regexp unless defined?(@@attribute_method_regexp) && @@attribute_method_regexp
51 @@attribute_method_regexp.match(method_name)
52 end
53
5b801b5 @NZKoz Change the implementation of ActiveRecord's attribute reader and writer ...
NZKoz authored
54 # Contains the names of the generated attribute methods.
55 def generated_methods #:nodoc:
56 @generated_methods ||= Set.new
57 end
c2b075b @josh Concernify AR AttributeMethods
josh authored
58
5b801b5 @NZKoz Change the implementation of ActiveRecord's attribute reader and writer ...
NZKoz authored
59 def generated_methods?
60 !generated_methods.empty?
61 end
c2b075b @josh Concernify AR AttributeMethods
josh authored
62
46f30f9 @lifo Merge documentation changes from docrails.
lifo authored
63 # Generates all the attribute related methods for columns in the database
64 # accessors, mutators and query methods.
5b801b5 @NZKoz Change the implementation of ActiveRecord's attribute reader and writer ...
NZKoz authored
65 def define_attribute_methods
66 return if generated_methods?
c2b075b @josh Concernify AR AttributeMethods
josh authored
67 columns_hash.keys.each do |name|
94dabf9 @josh Generate methods for all suffixes
josh authored
68 attribute_method_suffixes.each do |suffix|
c2b075b @josh Concernify AR AttributeMethods
josh authored
69 method_name = "#{name}#{suffix}"
70 unless instance_method_already_implemented?(method_name)
71 generate_method = "define_attribute_method#{suffix}"
72 if respond_to?(generate_method)
73 send(generate_method, name)
74 else
75 evaluate_attribute_method(name, "def #{method_name}(*args); attribute#{suffix}('#{name}', *args); end", method_name)
76 end
72385a7 @technoweenie Add Time Zone support to ActiveRecord, and config.time_zone property for...
technoweenie authored
77 end
5b801b5 @NZKoz Change the implementation of ActiveRecord's attribute reader and writer ...
NZKoz authored
78 end
79 end
80 end
acbec3e @NZKoz Ensure that custom mutators aren't redefined by define_attribute_methods...
NZKoz authored
81
e129c56 @josh Wrap up attribute method reset concerns in 'undefine_attribute_methods'
josh authored
82 def undefine_attribute_methods
83 generated_methods.each { |name| undef_method(name) }
84 @generated_methods = nil
85 end
86
46f30f9 @lifo Merge documentation changes from docrails.
lifo authored
87 # Checks whether the method is defined in the model or any of its subclasses
94dabf9 @josh Generate methods for all suffixes
josh authored
88 # that also derive from Active Record.
b31aa63 Allow column accessors to be created even if Kernel. or Object# methods ...
Tobias Lütke authored
89 def instance_method_already_implemented?(method_name)
240b4c5 @jeremy Ruby 1.9 compat: attribute methods
jeremy authored
90 method_name = method_name.to_s
94dabf9 @josh Generate methods for all suffixes
josh authored
91 @_defined_class_methods ||= ancestors.first(ancestors.index(ActiveRecord::Base)).sum([]) { |m| m.public_instance_methods(false) | m.private_instance_methods(false) | m.protected_instance_methods(false) }.map(&:to_s).to_set
5b2e8b1 @technoweenie Fix that ActiveRecord would create attribute methods and override custom...
technoweenie authored
92 @_defined_class_methods.include?(method_name)
b31aa63 Allow column accessors to be created even if Kernel. or Object# methods ...
Tobias Lütke authored
93 end
5b801b5 @NZKoz Change the implementation of ActiveRecord's attribute reader and writer ...
NZKoz authored
94
2b3cc24 @jeremy r4854@ks: jeremy | 2006-07-30 00:59:18 -0700
jeremy authored
95 private
96 # Suffixes a, ?, c become regexp /(a|\?|c)$/
97 def rebuild_attribute_method_regexp
98 suffixes = attribute_method_suffixes.map { |s| Regexp.escape(s) }
99 @@attribute_method_regexp = /(#{suffixes.join('|')})$/.freeze
100 end
101
102 def attribute_method_suffixes
103 @@attribute_method_suffixes ||= []
104 end
5b801b5 @NZKoz Change the implementation of ActiveRecord's attribute reader and writer ...
NZKoz authored
105
106 # Evaluate the definition for an attribute related method
c2b075b @josh Concernify AR AttributeMethods
josh authored
107 def evaluate_attribute_method(attr_name, method_definition, method_name)
94dabf9 @josh Generate methods for all suffixes
josh authored
108 generated_methods << method_name
5b801b5 @NZKoz Change the implementation of ActiveRecord's attribute reader and writer ...
NZKoz authored
109
110 begin
cff25aa @jeremy eval with __FILE__ and __LINE__
jeremy authored
111 class_eval(method_definition, __FILE__, __LINE__)
5b801b5 @NZKoz Change the implementation of ActiveRecord's attribute reader and writer ...
NZKoz authored
112 rescue SyntaxError => err
113 generated_methods.delete(attr_name)
114 if logger
115 logger.warn "Exception occurred during reader method compilation."
116 logger.warn "Maybe #{attr_name} is not a valid Ruby identifier?"
4d092ba @clemens Some performance goodness for AR.
clemens authored
117 logger.warn err.message
5b801b5 @NZKoz Change the implementation of ActiveRecord's attribute reader and writer ...
NZKoz authored
118 end
119 end
120 end
c2b075b @josh Concernify AR AttributeMethods
josh authored
121 end
5b801b5 @NZKoz Change the implementation of ActiveRecord's attribute reader and writer ...
NZKoz authored
122
46f30f9 @lifo Merge documentation changes from docrails.
lifo authored
123 # Allows access to the object attributes, which are held in the <tt>@attributes</tt> hash, as though they
0faa4ca @dhh Doc fix (closes #9323) [Henrik N]
dhh authored
124 # were first-class methods. So a Person class with a name attribute can use Person#name and
5b801b5 @NZKoz Change the implementation of ActiveRecord's attribute reader and writer ...
NZKoz authored
125 # Person#name= and never directly use the attributes hash -- except for multiple assigns with
126 # ActiveRecord#attributes=. A Milestone class can also ask Milestone#completed? to test that
46f30f9 @lifo Merge documentation changes from docrails.
lifo authored
127 # the completed attribute is not +nil+ or 0.
5b801b5 @NZKoz Change the implementation of ActiveRecord's attribute reader and writer ...
NZKoz authored
128 #
129 # It's also possible to instantiate related objects, so a Client class belonging to the clients
46f30f9 @lifo Merge documentation changes from docrails.
lifo authored
130 # table with a +master_id+ foreign key can instantiate master through Client#master.
5b801b5 @NZKoz Change the implementation of ActiveRecord's attribute reader and writer ...
NZKoz authored
131 def method_missing(method_id, *args, &block)
132 method_name = method_id.to_s
133
134 # If we haven't generated any methods yet, generate them, then
135 # see if we've created the method we're looking for.
136 if !self.class.generated_methods?
137 self.class.define_attribute_methods
d60d7ed @samg Make it so AR attributes which conflict with object-private methods (e.g...
samg authored
138 guard_private_attribute_method!(method_name, args)
5b801b5 @NZKoz Change the implementation of ActiveRecord's attribute reader and writer ...
NZKoz authored
139 if self.class.generated_methods.include?(method_name)
140 return self.send(method_id, *args, &block)
141 end
142 end
c2b075b @josh Concernify AR AttributeMethods
josh authored
143
d60d7ed @samg Make it so AR attributes which conflict with object-private methods (e.g...
samg authored
144 guard_private_attribute_method!(method_name, args)
5b801b5 @NZKoz Change the implementation of ActiveRecord's attribute reader and writer ...
NZKoz authored
145 if self.class.primary_key.to_s == method_name
146 id
147 elsif md = self.class.match_attribute_method?(method_name)
148 attribute_name, method_type = md.pre_match, md.to_s
149 if @attributes.include?(attribute_name)
150 __send__("attribute#{method_type}", attribute_name, *args, &block)
151 else
152 super
153 end
154 else
155 super
156 end
157 end
158
1646e8c @clemens More symbols for send and respond_to?.
clemens authored
159 # A Person object with a name attribute can ask <tt>person.respond_to?(:name)</tt>,
160 # <tt>person.respond_to?(:name=)</tt>, and <tt>person.respond_to?(:name?)</tt>
46f30f9 @lifo Merge documentation changes from docrails.
lifo authored
161 # which will all return +true+.
5b801b5 @NZKoz Change the implementation of ActiveRecord's attribute reader and writer ...
NZKoz authored
162 alias :respond_to_without_attributes? :respond_to?
4d9a7ab Changed ActiveRecord attributes to respect access control.
Adam Milligan authored
163 def respond_to?(method, include_private_methods = false)
5b801b5 @NZKoz Change the implementation of ActiveRecord's attribute reader and writer ...
NZKoz authored
164 method_name = method.to_s
165 if super
166 return true
f550c86 @alk Fix performance bug in AttibuteMethods#respond_to? in handling of privat...
alk authored
167 elsif !include_private_methods && super(method, true)
168 # If we're here than we haven't found among non-private methods
169 # but found among all methods. Which means that given method is private.
4d9a7ab Changed ActiveRecord attributes to respect access control.
Adam Milligan authored
170 return false
5b801b5 @NZKoz Change the implementation of ActiveRecord's attribute reader and writer ...
NZKoz authored
171 elsif !self.class.generated_methods?
172 self.class.define_attribute_methods
173 if self.class.generated_methods.include?(method_name)
174 return true
175 end
176 end
c2b075b @josh Concernify AR AttributeMethods
josh authored
177
586baf8 @josh read_attribute is always available through attribute
josh authored
178 if md = self.class.match_attribute_method?(method_name)
5b801b5 @NZKoz Change the implementation of ActiveRecord's attribute reader and writer ...
NZKoz authored
179 return true if @attributes.include?(md.pre_match)
180 end
181 super
182 end
2b3cc24 @jeremy r4854@ks: jeremy | 2006-07-30 00:59:18 -0700
jeremy authored
183
184 private
d60d7ed @samg Make it so AR attributes which conflict with object-private methods (e.g...
samg authored
185 # prevent method_missing from calling private methods with #send
186 def guard_private_attribute_method!(method_name, args)
187 if self.class.private_method_defined?(method_name)
188 raise NoMethodError.new("Attempt to call private method", method_name, args)
189 end
190 end
c2b075b @josh Concernify AR AttributeMethods
josh authored
191
5b801b5 @NZKoz Change the implementation of ActiveRecord's attribute reader and writer ...
NZKoz authored
192 def missing_attribute(attr_name, stack)
193 raise ActiveRecord::MissingAttributeError, "missing attribute: #{attr_name}", stack
194 end
2b3cc24 @jeremy r4854@ks: jeremy | 2006-07-30 00:59:18 -0700
jeremy authored
195 end
196 end
Something went wrong with that request. Please try again.