Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100755 1172 lines (1031 sloc) 55.665 kB
db045db @dhh Initial
dhh authored
1 require 'active_record/support/class_attribute_accessors'
2 require 'active_record/support/class_inheritable_attributes'
3 require 'active_record/support/inflector'
4 require 'yaml'
5
6 module ActiveRecord #:nodoc:
7 class ActiveRecordError < StandardError #:nodoc:
8 end
605bc77 @dhh Added a better exception for when a type column is used in a table wi…
dhh authored
9 class SubclassNotFound < ActiveRecordError #:nodoc:
10 end
db045db @dhh Initial
dhh authored
11 class AssociationTypeMismatch < ActiveRecordError #:nodoc:
12 end
13 class SerializationTypeMismatch < ActiveRecordError #:nodoc:
14 end
15 class AdapterNotSpecified < ActiveRecordError # :nodoc:
16 end
17 class AdapterNotFound < ActiveRecordError # :nodoc:
18 end
19 class ConnectionNotEstablished < ActiveRecordError #:nodoc:
20 end
21 class ConnectionFailed < ActiveRecordError #:nodoc:
22 end
23 class RecordNotFound < ActiveRecordError #:nodoc:
24 end
25 class StatementInvalid < ActiveRecordError #:nodoc:
26 end
554597d @dhh Added named bind-style variable interpolation #281 [Michael Koziarski]
dhh authored
27 class PreparedStatementInvalid < ActiveRecordError #:nodoc:
28 end
fbf9281 @dhh Added automated optimistic locking if the field lock_version is prese…
dhh authored
29 class StaleObjectError < ActiveRecordError #:nodoc:
30 end
db045db @dhh Initial
dhh authored
31
32 # Active Record objects doesn't specify their attributes directly, but rather infer them from the table definition with
33 # which they're linked. Adding, removing, and changing attributes and their type is done directly in the database. Any change
34 # is instantly reflected in the Active Record objects. The mapping that binds a given Active Record class to a certain
35 # database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.
36 #
37 # See the mapping rules in table_name and the full example in link:files/README.html for more insight.
38 #
39 # == Creation
40 #
41 # Active Records accepts constructor parameters either in a hash or as a block. The hash method is especially useful when
42 # you're receiving the data from somewhere else, like a HTTP request. It works like this:
43 #
44 # user = User.new("name" => "David", "occupation" => "Code Artist")
45 # user.name # => "David"
46 #
47 # You can also use block initialization:
48 #
49 # user = User.new do |u|
50 # u.name = "David"
51 # u.occupation = "Code Artist"
52 # end
53 #
54 # And of course you can just create a bare object and specify the attributes after the fact:
55 #
56 # user = User.new
57 # user.name = "David"
58 # user.occupation = "Code Artist"
59 #
60 # == Conditions
61 #
62 # Conditions can either be specified as a string or an array representing the WHERE-part of an SQL statement.
63 # The array form is to be used when the condition input is tainted and requires sanitization. The string form can
64 # be used for statements that doesn't involve tainted data. Examples:
65 #
66 # User < ActiveRecord::Base
67 # def self.authenticate_unsafely(user_name, password)
68 # find_first("user_name = '#{user_name}' AND password = '#{password}'")
69 # end
70 #
71 # def self.authenticate_safely(user_name, password)
3e7d191 @dhh Added bind-style variable interpolation for the condition arrays that…
dhh authored
72 # find_first([ "user_name = ? AND password = ?", user_name, password ])
db045db @dhh Initial
dhh authored
73 # end
74 # end
75 #
2575b3b @dhh Added extra words of caution for guarding against SQL-injection attacks
dhh authored
76 # The <tt>authenticate_unsafely</tt> method inserts the parameters directly into the query and is thus susceptible to SQL-injection
77 # attacks if the <tt>user_name</tt> and +password+ parameters come directly from a HTTP request. The <tt>authenticate_safely</tt> method,
78 # on the other hand, will sanitize the <tt>user_name</tt> and +password+ before inserting them in the query, which will ensure that
db045db @dhh Initial
dhh authored
79 # an attacker can't escape the query and fake the login (or worse).
2575b3b @dhh Added extra words of caution for guarding against SQL-injection attacks
dhh authored
80 #
db045db @dhh Initial
dhh authored
81 # == Overwriting default accessors
82 #
83 # All column values are automatically available through basic accessors on the Active Record object, but some times you
84 # want to specialize this behavior. This can be done by either by overwriting the default accessors (using the same
85 # name as the attribute) calling read_attribute(attr_name) and write_attribute(attr_name, value) to actually change things.
86 # Example:
87 #
88 # class Song < ActiveRecord::Base
89 # # Uses an integer of seconds to hold the length of the song
90 #
91 # def length=(minutes)
92 # write_attribute("length", minutes * 60)
93 # end
94 #
95 # def length
96 # read_attribute("length") / 60
97 # end
98 # end
99 #
ac8fd7d @dhh Added dynamic attribute-based finders as a cleaner way of getting obj…
dhh authored
100 # == Dynamic attribute-based finders
101 #
102 # Dynamic attribute-based finders are a cleaner way of getting objects by simple queries without turning to SQL. They work by
103 # appending the name of an attribute to <tt>find_by_</tt>, so you get finders like <tt>Person.find_by_user_name, Payment.find_by_transaction_id</tt>.
104 # So instead of writing <tt>Person.find_first(["user_name = ?", user_name])</tt>, you just do <tt>Person.find_by_user_name(user_name)</tt>.
105 #
106 # It's also possible to use multiple attributes in the same find by separating them with "_and_", so you get finders like
107 # <tt>Person.find_by_user_name_and_password</tt> or even <tt>Payment.find_by_purchaser_and_state_and_country</tt>. So instead of writing
108 # <tt>Person.find_first(["user_name = ? AND password = ?", user_name, password])</tt>, you just do
109 # <tt>Person.find_by_user_name_and_password(user_name, password)</tt>.
110 #
db045db @dhh Initial
dhh authored
111 # == Saving arrays, hashes, and other non-mappeable objects in text columns
112 #
113 # Active Record can serialize any object in text columns using YAML. To do so, you must specify this with a call to the class method +serialize+.
114 # This makes it possible to store arrays, hashes, and other non-mappeable objects without doing any additional work. Example:
115 #
116 # class User < ActiveRecord::Base
117 # serialize :preferences
118 # end
119 #
120 # user = User.create("preferences" => { "background" => "black", "display" => large })
121 # User.find(user.id).preferences # => { "background" => "black", "display" => large }
122 #
123 # You can also specify an optional :class_name option that'll raise an exception if a serialized object is retrieved as a
124 # descendent of a class not in the hierarchy. Example:
125 #
126 # class User < ActiveRecord::Base
127 # serialize :preferences, :class_name => "Hash"
128 # end
129 #
130 # user = User.create("preferences" => %w( one two three ))
131 # User.find(user.id).preferences # raises SerializationTypeMismatch
132 #
133 # == Single table inheritance
134 #
135 # Active Record allows inheritance by storing the name of the class in a column that by default is called "type" (can be changed
136 # by overwriting <tt>Base.inheritance_column</tt>). This means that an inheritance looking like this:
137 #
138 # class Company < ActiveRecord::Base; end
139 # class Firm < Company; end
140 # class Client < Company; end
141 # class PriorityClient < Client; end
142 #
143 # When you do Firm.create("name" => "37signals"), this record with be saved in the companies table with type = "Firm". You can then
144 # fetch this row again using Company.find_first "name = '37signals'" and it will return a Firm object.
145 #
f033833 @dhh Improving documentation...
dhh authored
146 # If you don't have a type column defined in your table, single-table inheritance won't be triggered. In that case, it'll work just
147 # like normal subclasses with no special magic for differentiating between them or reloading the right type with find.
148 #
db045db @dhh Initial
dhh authored
149 # Note, all the attributes for all the cases are kept in the same table. Read more:
150 # http://www.martinfowler.com/eaaCatalog/singleTableInheritance.html
151 #
152 # == Connection to multiple databases in different models
153 #
154 # Connections are usually created through ActiveRecord::Base.establish_connection and retrieved by ActiveRecord::Base.connection.
155 # All classes inheriting from ActiveRecord::Base will use this connection. But you can also set a class-specific connection.
156 # For example, if Course is a ActiveRecord::Base, but resides in a different database you can just say Course.establish_connection
157 # and Course *and all its subclasses* will use this connection instead.
158 #
159 # This feature is implemented by keeping a connection pool in ActiveRecord::Base that is a Hash indexed by the class. If a connection is
160 # requested, the retrieve_connection method will go up the class-hierarchy until a connection is found in the connection pool.
161 #
162 # == Exceptions
163 #
164 # * +ActiveRecordError+ -- generic error class and superclass of all other errors raised by Active Record
165 # * +AdapterNotSpecified+ -- the configuration hash used in <tt>establish_connection</tt> didn't include a
166 # <tt>:adapter</tt> key.
167 # * +AdapterNotSpecified+ -- the <tt>:adapter</tt> key used in <tt>establish_connection</tt> specified an unexisting adapter
168 # (or a bad spelling of an existing one).
169 # * +AssociationTypeMismatch+ -- the object assigned to the association wasn't of the type specified in the association definition.
170 # * +SerializationTypeMismatch+ -- the object serialized wasn't of the class specified in the <tt>:class_name</tt> option of
171 # the serialize definition.
172 # * +ConnectionNotEstablished+ -- no connection has been established. Use <tt>establish_connection</tt> before querying.
173 # * +RecordNotFound+ -- no record responded to the find* method.
174 # Either the row with the given ID doesn't exist or the row didn't meet the additional restrictions.
175 # * +StatementInvalid+ -- the database server rejected the SQL statement. The precise error is added in the message.
176 # Either the record with the given ID doesn't exist or the record didn't meet the additional restrictions.
177 #
178 # *Note*: The attributes listed are class-level attributes (accessible from both the class and instance level).
179 # So it's possible to assign a logger to the class through Base.logger= which will then be used by all
180 # instances in the current object space.
181 class Base
182 include ClassInheritableAttributes
183
184 # Accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, which is then passed
185 # on to any new database connections made and which can be retrieved on both a class and instance level by calling +logger+.
186 cattr_accessor :logger
187
188 # Returns the connection currently associated with the class. This can
189 # also be used to "borrow" the connection to do database work unrelated
190 # to any of the specific Active Records.
191 def self.connection
192 retrieve_connection
193 end
194
195 # Returns the connection currently associated with the class. This can
196 # also be used to "borrow" the connection to do database work that isn't
197 # easily done without going straight to SQL.
198 def connection
199 self.class.connection
200 end
201
202 def self.inherited(child) #:nodoc:
203 @@subclasses[self] ||= []
204 @@subclasses[self] << child
205 super
206 end
207
208 @@subclasses = {}
8e1f1ee @dhh Moved require_association to associations.rb and added methods for re…
dhh authored
209
db045db @dhh Initial
dhh authored
210 cattr_accessor :configurations
211 @@primary_key_prefix_type = {}
212
213 # Accessor for the prefix type that will be prepended to every primary key column name. The options are :table_name and
214 # :table_name_with_underscore. If the first is specified, the Product class will look for "productid" instead of "id" as
215 # the primary column. If the latter is specified, the Product class will look for "product_id" instead of "id". Remember
216 # that this is a global setting for all Active Records.
217 cattr_accessor :primary_key_prefix_type
218 @@primary_key_prefix_type = nil
219
220 # Accessor for the name of the prefix string to prepend to every table name. So if set to "basecamp_", all
221 # table names will be named like "basecamp_projects", "basecamp_people", etc. This is a convinient way of creating a namespace
222 # for tables in a shared database. By default, the prefix is the empty string.
223 cattr_accessor :table_name_prefix
224 @@table_name_prefix = ""
225
226 # Works like +table_name_prefix+, but appends instead of prepends (set to "_basecamp" gives "projects_basecamp",
227 # "people_basecamp"). By default, the suffix is the empty string.
228 cattr_accessor :table_name_suffix
229 @@table_name_suffix = ""
230
231 # Indicate whether or not table names should be the pluralized versions of the corresponding class names.
232 # If true, this the default table name for a +Product+ class will be +products+. If false, it would just be +product+.
233 # See table_name for the full rules on table/class naming. This is true, by default.
234 cattr_accessor :pluralize_table_names
235 @@pluralize_table_names = true
236
60de8c1 @dhh Added Base.default_timezone accessor that determines whether to use T…
dhh authored
237 # Determines whether to use Time.local (using :local) or Time.utc (using :utc) when pulling dates and times from the database.
238 # This is set to :local by default.
239 cattr_accessor :default_timezone
240 @@default_timezone = :local
241
db045db @dhh Initial
dhh authored
242 class << self # Class methods
243 # Returns objects for the records responding to either a specific id (1), a list of ids (1, 5, 6) or an array of ids.
244 # If only one ID is specified, that object is returned directly. If more than one ID is specified, an array is returned.
245 # Examples:
246 # Person.find(1) # returns the object for ID = 1
247 # Person.find(1, 2, 6) # returns an array for objects with IDs in (1, 2, 6)
248 # Person.find([7, 17]) # returns an array for objects with IDs in (7, 17)
57ed93e @dhh Fixed that Base#find will return an array if given an array -- regard…
dhh authored
249 # Person.find([1]) # returns an array for objects the object with ID = 1
6bd672e @dhh Added that Base#find takes an optional options hash, including :condi…
dhh authored
250 #
251 # The last argument may be a Hash of find options. Currently, +conditions+ is the only option, behaving the same as with +find_all+.
252 # Person.find(1, :conditions => "associate_id='5'"
253 # Person.find(1, 2, 6, :conditions => "status='active'"
254 # Person.find([7, 17], :conditions => ["sanitize_me='%s'", "bare'quote"]
255 #
db045db @dhh Initial
dhh authored
256 # +RecordNotFound+ is raised if no record can be found.
6bd672e @dhh Added that Base#find takes an optional options hash, including :condi…
dhh authored
257 def find(*args)
258 # Return an Array if ids are passed in an Array.
259 expects_array = args.first.kind_of?(Array)
260
261 # Extract options hash from argument list.
262 options = extract_options_from_args!(args)
263 conditions = " AND #{sanitize_sql(options[:conditions])}" if options[:conditions]
264
265 ids = args.flatten.compact.uniq
266 case ids.size
267
268 # Raise if no ids passed.
269 when 0
270 raise RecordNotFound, "Couldn't find #{name} without an ID#{conditions}"
271
272 # Find a single id.
273 when 1
274 unless result = find_first("#{primary_key} = #{sanitize(ids.first)}#{conditions}")
275 raise RecordNotFound, "Couldn't find #{name} with ID=#{ids.first}#{conditions}"
276 end
db045db @dhh Initial
dhh authored
277
6bd672e @dhh Added that Base#find takes an optional options hash, including :condi…
dhh authored
278 # Box result if expecting array.
279 expects_array ? [result] : result
db045db @dhh Initial
dhh authored
280
6bd672e @dhh Added that Base#find takes an optional options hash, including :condi…
dhh authored
281 # Find multiple ids.
db045db @dhh Initial
dhh authored
282 else
6bd672e @dhh Added that Base#find takes an optional options hash, including :condi…
dhh authored
283 ids_list = ids.map { |id| sanitize(id) }.join(',')
284 result = find_all("#{primary_key} IN (#{ids_list})#{conditions}", primary_key)
285 if result.size == ids.size
286 result
287 else
288 raise RecordNotFound, "Couldn't find #{name} with ID in (#{ids_list})#{conditions}"
289 end
db045db @dhh Initial
dhh authored
290 end
291 end
292
6bd672e @dhh Added that Base#find takes an optional options hash, including :condi…
dhh authored
293 # This method is deprecated in favor of find with the :conditions option.
db045db @dhh Initial
dhh authored
294 # Works like find, but the record matching +id+ must also meet the +conditions+.
295 # +RecordNotFound+ is raised if no record can be found matching the +id+ or meeting the condition.
296 # Example:
297 # Person.find_on_conditions 5, "first_name LIKE '%dav%' AND last_name = 'heinemeier'"
6bd672e @dhh Added that Base#find takes an optional options hash, including :condi…
dhh authored
298 def find_on_conditions(ids, conditions)
299 find(ids, :conditions => conditions)
db045db @dhh Initial
dhh authored
300 end
6bd672e @dhh Added that Base#find takes an optional options hash, including :condi…
dhh authored
301
db045db @dhh Initial
dhh authored
302 # Returns an array of all the objects that could be instantiated from the associated
303 # table in the database. The +conditions+ can be used to narrow the selection of objects (WHERE-part),
304 # such as by "color = 'red'", and arrangement of the selection can be done through +orderings+ (ORDER BY-part),
a775cb1 @dhh Added the option for sanitizing find_by_sql and the offset parts in r…
dhh authored
305 # such as by "last_name, first_name DESC". A maximum of returned objects and their offset can be specified in
306 # +limit+ (LIMIT...OFFSET-part). Examples:
db045db @dhh Initial
dhh authored
307 # Project.find_all "category = 'accounts'", "last_accessed DESC", 15
a775cb1 @dhh Added the option for sanitizing find_by_sql and the offset parts in r…
dhh authored
308 # Project.find_all ["category = ?", category_name], "created ASC", ["? OFFSET ?", 15, 20]
db045db @dhh Initial
dhh authored
309 def find_all(conditions = nil, orderings = nil, limit = nil, joins = nil)
310 sql = "SELECT * FROM #{table_name} "
311 sql << "#{joins} " if joins
312 add_conditions!(sql, conditions)
313 sql << "ORDER BY #{orderings} " unless orderings.nil?
4cd9c95 @dhh Added the possibility for adapters to overwrite add_limit! to impleme…
dhh authored
314
6bd672e @dhh Added that Base#find takes an optional options hash, including :condi…
dhh authored
315 connection.add_limit!(sql, sanitize_sql(limit)) unless limit.nil?
4cd9c95 @dhh Added the possibility for adapters to overwrite add_limit! to impleme…
dhh authored
316
db045db @dhh Initial
dhh authored
317 find_by_sql(sql)
318 end
319
a775cb1 @dhh Added the option for sanitizing find_by_sql and the offset parts in r…
dhh authored
320 # Works like find_all, but requires a complete SQL string. Examples:
db045db @dhh Initial
dhh authored
321 # Post.find_by_sql "SELECT p.*, c.author FROM posts p, comments c WHERE p.id = c.post_id"
a775cb1 @dhh Added the option for sanitizing find_by_sql and the offset parts in r…
dhh authored
322 # Post.find_by_sql ["SELECT * FROM posts WHERE author = ? AND created > ?", author_id, start_date]
db045db @dhh Initial
dhh authored
323 def find_by_sql(sql)
6bd672e @dhh Added that Base#find takes an optional options hash, including :condi…
dhh authored
324 connection.select_all(sanitize_sql(sql), "#{name} Load").inject([]) { |objects, record| objects << instantiate(record) }
db045db @dhh Initial
dhh authored
325 end
326
327 # Returns the object for the first record responding to the conditions in +conditions+,
328 # such as "group = 'master'". If more than one record is returned from the query, it's the first that'll
329 # be used to create the object. In such cases, it might be beneficial to also specify
330 # +orderings+, like "income DESC, name", to control exactly which record is to be used. Example:
331 # Employee.find_first "income > 50000", "income DESC, name"
332 def find_first(conditions = nil, orderings = nil)
6bd672e @dhh Added that Base#find takes an optional options hash, including :condi…
dhh authored
333 find_all(conditions, orderings, 1).first
db045db @dhh Initial
dhh authored
334 end
335
336 # Creates an object, instantly saves it as a record (if the validation permits it), and returns it. If the save
337 # fail under validations, the unsaved object is still returned.
338 def create(attributes = nil)
339 object = new(attributes)
340 object.save
341 object
342 end
343
344 # Finds the record from the passed +id+, instantly saves it with the passed +attributes+ (if the validation permits it),
345 # and returns it. If the save fail under validations, the unsaved object is still returned.
346 def update(id, attributes)
347 object = find(id)
348 object.attributes = attributes
349 object.save
350 object
351 end
352
648b8fd @dhh Added Base.destroy and Base.delete to remove records without holding …
dhh authored
353 # Deletes the record with the given +id+ without instantiating an object first.
354 def delete(id)
355 delete_all([ "#{primary_key} = ?", id ])
356 end
357
358 # Destroys the record with the given +id+ by instantiating the object and calling #destroy (all the callbacks are the triggered).
359 def destroy(id)
360 find(id).destroy
361 end
362
69cb942 @dhh Changed the interface on AbstractAdapter to require that adapters ret…
dhh authored
363 # Updates all records with the SET-part of an SQL update statement in +updates+ and returns an integer with the number of rows updates.
364 # A subset of the records can be selected by specifying +conditions+. Example:
db045db @dhh Initial
dhh authored
365 # Billing.update_all "category = 'authorized', approved = 1", "author = 'David'"
366 def update_all(updates, conditions = nil)
367 sql = "UPDATE #{table_name} SET #{updates} "
368 add_conditions!(sql, conditions)
69cb942 @dhh Changed the interface on AbstractAdapter to require that adapters ret…
dhh authored
369 return connection.update(sql, "#{name} Update")
db045db @dhh Initial
dhh authored
370 end
371
372 # Destroys the objects for all the records that matches the +condition+ by instantiating each object and calling
373 # the destroy method. Example:
374 # Person.destroy_all "last_login < '2004-04-04'"
375 def destroy_all(conditions = nil)
376 find_all(conditions).each { |object| object.destroy }
377 end
378
379 # Deletes all the records that matches the +condition+ without instantiating the objects first (and hence not
380 # calling the destroy method). Example:
381 # Post.destroy_all "person_id = 5 AND (category = 'Something' OR category = 'Else')"
382 def delete_all(conditions = nil)
383 sql = "DELETE FROM #{table_name} "
384 add_conditions!(sql, conditions)
385 connection.delete(sql, "#{name} Delete all")
386 end
387
388 # Returns the number of records that meets the +conditions+. Zero is returned if no records match. Example:
389 # Product.count "sales > 1"
390 def count(conditions = nil)
391 sql = "SELECT COUNT(*) FROM #{table_name} "
392 add_conditions!(sql, conditions)
393 count_by_sql(sql)
394 end
395
396 # Returns the result of an SQL statement that should only include a COUNT(*) in the SELECT part.
397 # Product.count "SELECT COUNT(*) FROM sales s, customers c WHERE s.customer_id = c.id"
398 def count_by_sql(sql)
a775cb1 @dhh Added the option for sanitizing find_by_sql and the offset parts in r…
dhh authored
399 sql = sanitize_conditions(sql)
db045db @dhh Initial
dhh authored
400 count = connection.select_one(sql, "#{name} Count").values.first
401 return count ? count.to_i : 0
402 end
403
404 # Increments the specified counter by one. So <tt>DiscussionBoard.increment_counter("post_count",
405 # discussion_board_id)</tt> would increment the "post_count" counter on the board responding to discussion_board_id.
406 # This is used for caching aggregate values, so that they doesn't need to be computed every time. Especially important
407 # for looping over a collection where each element require a number of aggregate values. Like the DiscussionBoard
408 # that needs to list both the number of posts and comments.
409 def increment_counter(counter_name, id)
4940383 @dhh Fixed value quoting in all generated SQL statements, so that integers…
dhh authored
410 update_all "#{counter_name} = #{counter_name} + 1", "#{primary_key} = #{quote(id)}"
db045db @dhh Initial
dhh authored
411 end
412
413 # Works like increment_counter, but decrements instead.
414 def decrement_counter(counter_name, id)
4940383 @dhh Fixed value quoting in all generated SQL statements, so that integers…
dhh authored
415 update_all "#{counter_name} = #{counter_name} - 1", "#{primary_key} = #{quote(id)}"
db045db @dhh Initial
dhh authored
416 end
417
418 # Attributes named in this macro are protected from mass-assignment, such as <tt>new(attributes)</tt> and
419 # <tt>attributes=(attributes)</tt>. Their assignment will simply be ignored. Instead, you can use the direct writer
420 # methods to do assignment. This is meant to protect sensitive attributes to be overwritten by URL/form hackers. Example:
421 #
422 # class Customer < ActiveRecord::Base
423 # attr_protected :credit_rating
424 # end
425 #
426 # customer = Customer.new("name" => David, "credit_rating" => "Excellent")
427 # customer.credit_rating # => nil
428 # customer.attributes = { "description" => "Jolly fellow", "credit_rating" => "Superb" }
429 # customer.credit_rating # => nil
430 #
431 # customer.credit_rating = "Average"
432 # customer.credit_rating # => "Average"
433 def attr_protected(*attributes)
434 write_inheritable_array("attr_protected", attributes)
435 end
436
437 # Returns an array of all the attributes that have been protected from mass-assigment.
438 def protected_attributes # :nodoc:
439 read_inheritable_attribute("attr_protected")
440 end
441
442 # If this macro is used, only those attributed named in it will be accessible for mass-assignment, such as
443 # <tt>new(attributes)</tt> and <tt>attributes=(attributes)</tt>. This is the more conservative choice for mass-assignment
444 # protection. If you'd rather start from an all-open default and restrict attributes as needed, have a look at
445 # attr_protected.
446 def attr_accessible(*attributes)
447 write_inheritable_array("attr_accessible", attributes)
448 end
449
450 # Returns an array of all the attributes that have been made accessible to mass-assigment.
451 def accessible_attributes # :nodoc:
452 read_inheritable_attribute("attr_accessible")
453 end
454
455 # Specifies that the attribute by the name of +attr_name+ should be serialized before saving to the database and unserialized
456 # after loading from the database. The serialization is done through YAML. If +class_name+ is specified, the serialized
457 # object must be of that class on retrival or +SerializationTypeMismatch+ will be raised.
458 def serialize(attr_name, class_name = Object)
459 write_inheritable_attribute("attr_serialized", serialized_attributes.update(attr_name.to_s => class_name))
460 end
461
462 # Returns a hash of all the attributes that have been specified for serialization as keys and their class restriction as values.
463 def serialized_attributes
464 read_inheritable_attribute("attr_serialized") || { }
465 end
466
467 # Guesses the table name (in forced lower-case) based on the name of the class in the inheritance hierarchy descending
468 # directly from ActiveRecord. So if the hierarchy looks like: Reply < Message < ActiveRecord, then Message is used
469 # to guess the table name from even when called on Reply. The guessing rules are as follows:
470 #
471 # * Class name ends in "x", "ch" or "ss": "es" is appended, so a Search class becomes a searches table.
472 # * Class name ends in "y" preceded by a consonant or "qu": The "y" is replaced with "ies", so a Category class becomes a categories table.
473 # * Class name ends in "fe": The "fe" is replaced with "ves", so a Wife class becomes a wives table.
474 # * Class name ends in "lf" or "rf": The "f" is replaced with "ves", so a Half class becomes a halves table.
475 # * Class name ends in "person": The "person" is replaced with "people", so a Salesperson class becomes a salespeople table.
476 # * Class name ends in "man": The "man" is replaced with "men", so a Spokesman class becomes a spokesmen table.
477 # * Class name ends in "sis": The "i" is replaced with an "e", so a Basis class becomes a bases table.
478 # * Class name ends in "tum" or "ium": The "um" is replaced with an "a", so a Datum class becomes a data table.
479 # * Class name ends in "child": The "child" is replaced with "children", so a NodeChild class becomes a node_children table.
480 # * Class name ends in an "s": No additional characters are added or removed.
481 # * Class name doesn't end in "s": An "s" is appended, so a Comment class becomes a comments table.
482 # * Class name with word compositions: Compositions are underscored, so CreditCard class becomes a credit_cards table.
483 #
484 # Additionally, the class-level table_name_prefix is prepended to the table_name and the table_name_suffix is appended.
485 # So if you have "myapp_" as a prefix, the table name guess for an Account class becomes "myapp_accounts".
486 #
487 # You can also overwrite this class method to allow for unguessable links, such as a Mouse class with a link to a
488 # "mice" table. Example:
489 #
490 # class Mouse < ActiveRecord::Base
491 # def self.table_name() "mice" end
492 # end
dcc4868 @dhh Fixed that Base.table_name would expect a parameter when used in has_…
dhh authored
493 def table_name
494 table_name_prefix + undecorated_table_name(class_name_of_active_record_descendant(self)) + table_name_suffix
db045db @dhh Initial
dhh authored
495 end
496
497 # Defines the primary key field -- can be overridden in subclasses. Overwritting will negate any effect of the
498 # primary_key_prefix_type setting, though.
499 def primary_key
500 case primary_key_prefix_type
501 when :table_name
502 Inflector.foreign_key(class_name_of_active_record_descendant(self), false)
503 when :table_name_with_underscore
504 Inflector.foreign_key(class_name_of_active_record_descendant(self))
505 else
506 "id"
507 end
508 end
509
510 # Defines the column name for use with single table inheritance -- can be overridden in subclasses.
511 def inheritance_column
512 "type"
513 end
514
515 # Turns the +table_name+ back into a class name following the reverse rules of +table_name+.
516 def class_name(table_name = table_name) # :nodoc:
517 # remove any prefix and/or suffix from the table name
518 class_name = Inflector.camelize(table_name[table_name_prefix.length..-(table_name_suffix.length + 1)])
519 class_name = Inflector.singularize(class_name) if pluralize_table_names
520 return class_name
521 end
522
523 # Returns an array of column objects for the table associated with this class.
524 def columns
525 @columns ||= connection.columns(table_name, "#{name} Columns")
526 end
527
528 # Returns an array of column objects for the table associated with this class.
529 def columns_hash
530 @columns_hash ||= columns.inject({}) { |hash, column| hash[column.name] = column; hash }
531 end
532
533 # Returns an array of columns objects where the primary id, all columns ending in "_id" or "_count",
534 # and columns used for single table inheritance has been removed.
535 def content_columns
536 @content_columns ||= columns.reject { |c| c.name == primary_key || c.name =~ /(_id|_count)$/ || c.name == inheritance_column }
537 end
538
539 # Returns a hash of all the methods added to query each of the columns in the table with the name of the method as the key
540 # and true as the value. This makes it possible to do O(1) lookups in respond_to? to check if a given method for attribute
541 # is available.
542 def column_methods_hash
543 @dynamic_methods_hash ||= columns_hash.keys.inject(Hash.new(false)) do |methods, attr|
544 methods[attr.to_sym] = true
545 methods["#{attr}=".to_sym] = true
546 methods["#{attr}?".to_sym] = true
dad37cf @dhh FormHelper should only use *_before_type_cast if they available on th…
dhh authored
547 methods["#{attr}_before_type_cast".to_sym] = true
db045db @dhh Initial
dhh authored
548 methods
549 end
550 end
1314f48 @dhh Added methods for resetting the cached information on classes that yo…
dhh authored
551
552 # Resets all the cached information about columns, which will cause they to be reloaded on the next request.
553 def reset_column_information
554 @columns = @columns_hash = @content_columns = @dynamic_methods_hash = nil
555 end
556
557 def reset_column_information_and_inheritable_attributes_for_all_subclasses
558 subclasses.each { |klass| klass.reset_inheritable_attributes; klass.reset_column_information }
559 end
db045db @dhh Initial
dhh authored
560
561 # Transforms attribute key names into a more humane format, such as "First name" instead of "first_name". Example:
562 # Person.human_attribute_name("first_name") # => "First name"
563 def human_attribute_name(attribute_key_name)
564 attribute_key_name.gsub(/_/, " ").capitalize unless attribute_key_name.nil?
565 end
566
567 def descends_from_active_record? # :nodoc:
605bc77 @dhh Added a better exception for when a type column is used in a table wi…
dhh authored
568 superclass == Base || !columns_hash.has_key?(inheritance_column)
db045db @dhh Initial
dhh authored
569 end
570
4940383 @dhh Fixed value quoting in all generated SQL statements, so that integers…
dhh authored
571 def quote(object)
572 connection.quote(object)
573 end
574
575 # Used to sanitize objects before they're used in an SELECT SQL-statement. Delegates to <tt>connection.quote</tt>.
db045db @dhh Initial
dhh authored
576 def sanitize(object) # :nodoc:
4940383 @dhh Fixed value quoting in all generated SQL statements, so that integers…
dhh authored
577 connection.quote(object)
db045db @dhh Initial
dhh authored
578 end
579
580 # Used to aggregate logging and benchmark, so you can measure and represent multiple statements in a single block.
581 # Usage (hides all the SQL calls for the individual actions and calculates total runtime for them all):
582 #
583 # Project.benchmark("Creating project") do
584 # project = Project.create("name" => "stuff")
585 # project.create_manager("name" => "David")
586 # project.milestones << Milestone.find_all
587 # end
588 def benchmark(title)
589 result = nil
590 logger.level = Logger::ERROR
591 bm = Benchmark.measure { result = yield }
592 logger.level = Logger::DEBUG
593 logger.info "#{title} (#{sprintf("%f", bm.real)})"
594 return result
595 end
596
597 private
598 # Finder methods must instantiate through this method to work with the single-table inheritance model
599 # that makes it possible to create objects of different types from the same table.
600 def instantiate(record)
605bc77 @dhh Added a better exception for when a type column is used in a table wi…
dhh authored
601 require_association_class(record[inheritance_column])
602
603 begin
604 object = record_with_type?(record) ? compute_type(record[inheritance_column]).allocate : allocate
605 rescue NameError
606 raise(
607 SubclassNotFound,
608 "The single-table inheritance mechanism failed to locate the subclass: '#{record[inheritance_column]}'. " +
609 "This error is raised because the column '#{inheritance_column}' is reserved for storing the class in case of inheritance. " +
610 "Please rename this column if you didn't intend it to be used for storing the inheritance class " +
611 "or overwrite #{self.to_s}.inheritance_column to use another column for that information."
612 )
613 end
614
db045db @dhh Initial
dhh authored
615 object.instance_variable_set("@attributes", record)
616 return object
617 end
618
619 # Returns true if the +record+ has a single table inheritance column and is using it.
620 def record_with_type?(record)
621 record.include?(inheritance_column) && !record[inheritance_column].nil? &&
622 !record[inheritance_column].empty?
623 end
624
625 # Returns the name of the type of the record using the current module as a prefix. So descendents of
626 # MyApp::Business::Account would be appear as "MyApp::Business::AccountSubclass".
627 def type_name_with_module(type_name)
628 self.name =~ /::/ ? self.name.scan(/(.*)::/).first.first + "::" + type_name : type_name
629 end
630
631 # Adds a sanitized version of +conditions+ to the +sql+ string. Note that it's the passed +sql+ string is changed.
632 def add_conditions!(sql, conditions)
6bd672e @dhh Added that Base#find takes an optional options hash, including :condi…
dhh authored
633 sql << "WHERE #{sanitize_sql(conditions)} " unless conditions.nil?
db045db @dhh Initial
dhh authored
634 sql << (conditions.nil? ? "WHERE " : " AND ") + type_condition unless descends_from_active_record?
635 end
636
637 def type_condition
638 " (" + subclasses.inject("#{inheritance_column} = '#{Inflector.demodulize(name)}' ") do |condition, subclass|
4940383 @dhh Fixed value quoting in all generated SQL statements, so that integers…
dhh authored
639 condition << "OR #{inheritance_column} = '#{Inflector.demodulize(subclass.name)}' "
db045db @dhh Initial
dhh authored
640 end + ") "
641 end
642
643 # Guesses the table name, but does not decorate it with prefix and suffix information.
644 def undecorated_table_name(class_name = class_name_of_active_record_descendant(self))
645 table_name = Inflector.underscore(Inflector.demodulize(class_name))
646 table_name = Inflector.pluralize(table_name) if pluralize_table_names
647 return table_name
648 end
649
ac8fd7d @dhh Added dynamic attribute-based finders as a cleaner way of getting obj…
dhh authored
650 # Enables dynamic finders like find_by_user_name(user_name) and find_by_user_name_and_password(user_name, password) that are turned into
651 # find_first(["user_name = ?", user_name]) and find_first(["user_name = ? AND password = ?", user_name, password]) respectively.
652 def method_missing(method_id, *arguments)
653 method_name = method_id.id2name
654
655 if method_name =~ /find_by_([_a-z]+)/
656 attributes = $1.split("_and_")
657 attributes.each { |attr_name| super unless column_methods_hash[attr_name.intern] }
658 conditions = attributes.collect { |attr_name| "#{attr_name} = ? "}.join(" AND ")
659 find_first([conditions, *arguments])
660 else
661 super
662 end
663 end
db045db @dhh Initial
dhh authored
664
665 protected
666 def subclasses
667 @@subclasses[self] ||= []
668 @@subclasses[self] + extra = @@subclasses[self].inject([]) {|list, subclass| list + subclass.subclasses }
669 end
670
671 # Returns the class type of the record using the current module as a prefix. So descendents of
672 # MyApp::Business::Account would be appear as MyApp::Business::AccountSubclass.
673 def compute_type(type_name)
674 type_name_with_module(type_name).split("::").inject(Object) do |final_type, part|
675 final_type = final_type.const_get(part)
676 end
677 end
678
679 # Returns the name of the class descending directly from ActiveRecord in the inheritance hierarchy.
680 def class_name_of_active_record_descendant(klass)
681 if klass.superclass == Base
682 return klass.name
683 elsif klass.superclass.nil?
684 raise ActiveRecordError, "#{name} doesn't belong in a hierarchy descending from ActiveRecord"
685 else
686 class_name_of_active_record_descendant(klass.superclass)
687 end
688 end
689
6bd672e @dhh Added that Base#find takes an optional options hash, including :condi…
dhh authored
690 # Accepts an array or string. The string is returned untouched, but the array has each value
691 # sanitized and interpolated into the sql statement.
692 # ["name='%s' and group_id='%s'", "foo'bar", 4] returns "name='foo''bar' and group_id='4'"
693 def sanitize_sql(ary)
694 return ary unless ary.is_a?(Array)
3e7d191 @dhh Added bind-style variable interpolation for the condition arrays that…
dhh authored
695
6bd672e @dhh Added that Base#find takes an optional options hash, including :condi…
dhh authored
696 statement, *values = ary
697 if values.first.is_a?(Hash) and statement =~ /:\w+/
698 replace_named_bind_variables(statement, values.first)
699 elsif statement.include?('?')
554597d @dhh Added named bind-style variable interpolation #281 [Michael Koziarski]
dhh authored
700 replace_bind_variables(statement, values)
701 else
4940383 @dhh Fixed value quoting in all generated SQL statements, so that integers…
dhh authored
702 statement % values.collect { |value| connection.quote_string(value.to_s) }
554597d @dhh Added named bind-style variable interpolation #281 [Michael Koziarski]
dhh authored
703 end
3e7d191 @dhh Added bind-style variable interpolation for the condition arrays that…
dhh authored
704 end
705
6bd672e @dhh Added that Base#find takes an optional options hash, including :condi…
dhh authored
706 alias_method :sanitize_conditions, :sanitize_sql
707
3e7d191 @dhh Added bind-style variable interpolation for the condition arrays that…
dhh authored
708 def replace_bind_variables(statement, values)
9322168 @dhh Restored bind arity checking #412 [bitsweat]
dhh authored
709 raise_if_bind_arity_mismatch(statement, statement.count('?'), values.size)
6bd672e @dhh Added that Base#find takes an optional options hash, including :condi…
dhh authored
710 bound = values.dup
711 statement.gsub('?') { connection.quote(bound.shift) }
554597d @dhh Added named bind-style variable interpolation #281 [Michael Koziarski]
dhh authored
712 end
713
6bd672e @dhh Added that Base#find takes an optional options hash, including :condi…
dhh authored
714 def replace_named_bind_variables(statement, bind_vars)
9322168 @dhh Restored bind arity checking #412 [bitsweat]
dhh authored
715 raise_if_bind_arity_mismatch(statement, statement.scan(/:(\w+)/).uniq.size, bind_vars.size)
6bd672e @dhh Added that Base#find takes an optional options hash, including :condi…
dhh authored
716 statement.gsub(/:(\w+)/) do
717 match = $1.to_sym
718 if bind_vars.has_key?(match)
719 connection.quote(bind_vars[match])
720 else
721 raise PreparedStatementInvalid, "missing value for :#{match} in #{statement}"
554597d @dhh Added named bind-style variable interpolation #281 [Michael Koziarski]
dhh authored
722 end
723 end
9322168 @dhh Restored bind arity checking #412 [bitsweat]
dhh authored
724 end
725
726 def raise_if_bind_arity_mismatch(statement, expected, provided)
727 unless expected == provided
728 raise PreparedStatementInvalid, "wrong number of bind variables (#{provided} for #{expected}) in: #{statement}"
729 end
6bd672e @dhh Added that Base#find takes an optional options hash, including :condi…
dhh authored
730 end
554597d @dhh Added named bind-style variable interpolation #281 [Michael Koziarski]
dhh authored
731
6bd672e @dhh Added that Base#find takes an optional options hash, including :condi…
dhh authored
732 def extract_options_from_args!(args)
733 if args.last.is_a?(Hash) then args.pop else {} end
db045db @dhh Initial
dhh authored
734 end
aaf9a45 @dhh Added Base.validate_uniqueness thatv alidates whether the value of th…
dhh authored
735
736 def encode_quoted_value(value)
737 quoted_value = connection.quote(value)
738 quoted_value = "'#{quoted_value[1..-2].gsub(/\'/, "\\\\'")}'" if quoted_value.include?("\\\'")
739 quoted_value
740 end
db045db @dhh Initial
dhh authored
741 end
742
743 public
744 # New objects can be instantiated as either empty (pass no construction parameter) or pre-set with
745 # attributes but not yet saved (pass a hash with key names matching the associated table column names).
746 # In both instances, valid attribute keys are determined by the column names of the associated table --
747 # hence you can't have attributes that aren't part of the table columns.
748 def initialize(attributes = nil)
749 @attributes = attributes_from_column_definition
750 @new_record = true
751 ensure_proper_type
752 self.attributes = attributes unless attributes.nil?
753 yield self if block_given?
754 end
755
756 # Every Active Record class must use "id" as their primary ID. This getter overwrites the native
757 # id method, which isn't being used in this context.
758 def id
759 read_attribute(self.class.primary_key)
760 end
761
3e5a880 @dhh Switched strategy on the id_before_type_cast problem and just did an …
dhh authored
762 def id_before_type_cast
763 read_attribute_before_type_cast(self.class.primary_key)
764 end
765
4940383 @dhh Fixed value quoting in all generated SQL statements, so that integers…
dhh authored
766 def quoted_id
767 quote(id, self.class.columns_hash[self.class.primary_key])
768 end
769
db045db @dhh Initial
dhh authored
770 # Sets the primary ID.
771 def id=(value)
772 write_attribute(self.class.primary_key, value)
773 end
774
775 # Returns true if this object hasn't been saved yet -- that is, a record for the object doesn't exist yet.
776 def new_record?
777 @new_record
778 end
779
780 # * No record exists: Creates a new record with values matching those of the object attributes.
781 # * A record does exist: Updates the record with values matching those of the object attributes.
782 def save
783 create_or_update
784 return true
785 end
786
787 # Deletes the record in the database and freezes this instance to reflect that no changes should
788 # be made (since they can't be persisted).
789 def destroy
790 unless new_record?
791 connection.delete(
792 "DELETE FROM #{self.class.table_name} " +
4940383 @dhh Fixed value quoting in all generated SQL statements, so that integers…
dhh authored
793 "WHERE #{self.class.primary_key} = #{quote(id)}",
db045db @dhh Initial
dhh authored
794 "#{self.class.name} Destroy"
795 )
796 end
797
798 freeze
799 end
800
801 # Returns a clone of the record that hasn't been assigned an id yet and is treated as a new record.
802 def clone
803 attr = Hash.new
804
805 self.attribute_names.each do |name|
806 begin
807 attr[name] = read_attribute(name).clone
808 rescue TypeError
809 attr[name] = read_attribute(name)
810 end
811 end
812
813 cloned_record = self.class.new(attr)
814 cloned_record.instance_variable_set "@new_record", true
815 cloned_record.id = nil
816 cloned_record
817 end
818
819 # Updates a single attribute and saves the record. This is especially useful for boolean flags on existing records.
d678997 @dhh Base#update_attribute isnt subject to validation
dhh authored
820 # Note: This method is overwritten by the Validation module that'll make sure that updates made with this method
821 # doesn't get subjected to validation checks. Hence, attributes can be updated even if the full object isn't valid.
db045db @dhh Initial
dhh authored
822 def update_attribute(name, value)
823 self[name] = value
d678997 @dhh Base#update_attribute isnt subject to validation
dhh authored
824 return true
604a094 @dhh Added Base#update_attributes that'll accept a hash of attributes and …
dhh authored
825 end
826
d678997 @dhh Base#update_attribute isnt subject to validation
dhh authored
827 # Updates all the attributes in from the passed hash and saves the record. If the object is invalid, the saving will
828 # fail and false will be returned.
604a094 @dhh Added Base#update_attributes that'll accept a hash of attributes and …
dhh authored
829 def update_attributes(attributes)
3bef4c2 @dhh Made Base#update_attributes actually work
dhh authored
830 self.attributes = attributes
604a094 @dhh Added Base#update_attributes that'll accept a hash of attributes and …
dhh authored
831 return save
db045db @dhh Initial
dhh authored
832 end
833
834 # Returns the value of attribute identified by <tt>attr_name</tt> after it has been type cast (for example,
835 # "2004-12-12" in a data column is cast to a date object, like Date.new(2004, 12, 12)).
836 # (Alias for the protected read_attribute method).
837 def [](attr_name)
838 read_attribute(attr_name)
839 end
840
841 # Updates the attribute identified by <tt>attr_name</tt> with the specified +value+.
842 # (Alias for the protected write_attribute method).
843 def []= (attr_name, value)
844 write_attribute(attr_name, value)
845 end
846
847 # Allows you to set all the attributes at once by passing in a hash with keys
848 # matching the attribute names (which again matches the column names). Sensitive attributes can be protected
849 # from this form of mass-assignment by using the +attr_protected+ macro. Or you can alternatively
850 # specify which attributes *can* be accessed in with the +attr_accessible+ macro. Then all the
851 # attributes not included in that won't be allowed to be mass-assigned.
852 def attributes=(attributes)
853 return if attributes.nil?
854
855 multi_parameter_attributes = []
856 remove_attributes_protected_from_mass_assignment(attributes).each do |k, v|
857 k.include?("(") ? multi_parameter_attributes << [ k, v ] : send(k + "=", v)
858 end
859 assign_multiparameter_attributes(multi_parameter_attributes)
860 end
861
862 # Returns true if the specified +attribute+ has been set by the user or by a database load and is neither
863 # nil nor empty? (the latter only applies to objects that responds to empty?, most notably Strings).
864 def attribute_present?(attribute)
865 is_empty = read_attribute(attribute).respond_to?("empty?") ? read_attribute(attribute).empty? : false
866 @attributes.include?(attribute) && !@attributes[attribute].nil? && !is_empty
867 end
868
869 # Returns an array of names for the attributes available on this object sorted alphabetically.
870 def attribute_names
871 @attributes.keys.sort
872 end
873
874 # Returns the column object for the named attribute.
875 def column_for_attribute(name)
876 self.class.columns_hash[name]
877 end
878
879 # Returns true if the +comparison_object+ is of the same type and has the same id.
880 def ==(comparison_object)
881 comparison_object.instance_of?(self.class) && comparison_object.id == id
882 end
883
884 # Delegates to ==
885 def eql?(comparison_object)
886 self == (comparison_object)
887 end
888
889 # Delegates to id in order to allow two records of the same type and id to work with something like:
890 # [ Person.find(1), Person.find(2), Person.find(3) ] & [ Person.find(1), Person.find(4) ] # => [ Person.find(1) ]
891 def hash
892 id
893 end
894
895 # For checking respond_to? without searching the attributes (which is faster).
896 alias_method :respond_to_without_attributes?, :respond_to?
897
898 # A Person object with a name attribute can ask person.respond_to?("name"), person.respond_to?("name="), and
899 # person.respond_to?("name?") which will all return true.
900 def respond_to?(method)
901 self.class.column_methods_hash[method.to_sym] || respond_to_without_attributes?(method)
902 end
d82f73e @dhh Abolished ActionController::Base.require_or_load in favor of require_…
dhh authored
903
db045db @dhh Initial
dhh authored
904 private
905 def create_or_update
906 if new_record? then create else update end
907 end
908
909 # Updates the associated record with values matching those of the instant attributes.
910 def update
911 connection.update(
912 "UPDATE #{self.class.table_name} " +
9a248a8 @dhh Dont include the primary key in updates -- its unneeded and SQL Serve…
dhh authored
913 "SET #{quoted_comma_pair_list(connection, attributes_with_quotes(false))} " +
4940383 @dhh Fixed value quoting in all generated SQL statements, so that integers…
dhh authored
914 "WHERE #{self.class.primary_key} = #{quote(id)}",
db045db @dhh Initial
dhh authored
915 "#{self.class.name} Update"
916 )
917 end
918
919 # Creates a new record with values matching those of the instant attributes.
920 def create
921 self.id = connection.insert(
922 "INSERT INTO #{self.class.table_name} " +
923 "(#{quoted_column_names.join(', ')}) " +
924 "VALUES(#{attributes_with_quotes.values.join(', ')})",
925 "#{self.class.name} Create",
926 self.class.primary_key, self.id
927 )
928
929 @new_record = false
930 end
931
932 # Sets the attribute used for single table inheritance to this class name if this is not the ActiveRecord descendant.
933 # Considering the hierarchy Reply < Message < ActiveRecord, this makes it possible to do Reply.new without having to
934 # set Reply[Reply.inheritance_column] = "Reply" yourself. No such attribute would be set for objects of the
935 # Message class in that example.
936 def ensure_proper_type
937 unless self.class.descends_from_active_record?
938 write_attribute(self.class.inheritance_column, Inflector.demodulize(self.class.name))
939 end
940 end
941
942 # Allows access to the object attributes, which are held in the @attributes hash, as were
943 # they first-class methods. So a Person class with a name attribute can use Person#name and
944 # Person#name= and never directly use the attributes hash -- except for multiple assigns with
945 # ActiveRecord#attributes=. A Milestone class can also ask Milestone#completed? to test that
946 # the completed attribute is not nil or 0.
947 #
948 # It's also possible to instantiate related objects, so a Client class belonging to the clients
949 # table with a master_id foreign key can instantiate master through Client#master.
950 def method_missing(method_id, *arguments)
951 method_name = method_id.id2name
daf3e92 @dhh Added a db2 adapter that only depends on the Ruby/DB2 bindings (http:…
dhh authored
952
db045db @dhh Initial
dhh authored
953 if method_name =~ read_method? && @attributes.include?($1)
954 return read_attribute($1)
7b5ed66 @dhh Added respondence to *_before_type_cast for all attributes to return …
dhh authored
955 elsif method_name =~ read_untyped_method? && @attributes.include?($1)
956 return read_attribute_before_type_cast($1)
db045db @dhh Initial
dhh authored
957 elsif method_name =~ write_method? && @attributes.include?($1)
958 write_attribute($1, arguments[0])
959 elsif method_name =~ query_method? && @attributes.include?($1)
960 return query_attribute($1)
961 else
962 super
963 end
964 end
965
7b5ed66 @dhh Added respondence to *_before_type_cast for all attributes to return …
dhh authored
966 def read_method?() /^([a-zA-Z][-_\w]*)[^=?]*$/ end
967 def read_untyped_method?() /^([a-zA-Z][-_\w]*)_before_type_cast$/ end
968 def write_method?() /^([a-zA-Z][-_\w]*)=.*$/ end
969 def query_method?() /^([a-zA-Z][-_\w]*)\?$/ end
db045db @dhh Initial
dhh authored
970
7b5ed66 @dhh Added respondence to *_before_type_cast for all attributes to return …
dhh authored
971 # Returns the value of attribute identified by <tt>attr_name</tt> after it has been type cast (for example,
db045db @dhh Initial
dhh authored
972 # "2004-12-12" in a data column is cast to a date object, like Date.new(2004, 12, 12)).
973 def read_attribute(attr_name) #:doc:
974 if @attributes.keys.include? attr_name
975 if column = column_for_attribute(attr_name)
7b5ed66 @dhh Added respondence to *_before_type_cast for all attributes to return …
dhh authored
976 unserializable_attribute?(attr_name, column) ?
db045db @dhh Initial
dhh authored
977 unserialize_attribute(attr_name) : column.type_cast(@attributes[attr_name])
7b5ed66 @dhh Added respondence to *_before_type_cast for all attributes to return …
dhh authored
978 else
979 @attributes[attr_name]
db045db @dhh Initial
dhh authored
980 end
981 else
982 nil
983 end
984 end
985
7b5ed66 @dhh Added respondence to *_before_type_cast for all attributes to return …
dhh authored
986 def read_attribute_before_type_cast(attr_name)
987 @attributes[attr_name]
988 end
989
db045db @dhh Initial
dhh authored
990 # Returns true if the attribute is of a text column and marked for serialization.
991 def unserializable_attribute?(attr_name, column)
daf3e92 @dhh Added a db2 adapter that only depends on the Ruby/DB2 bindings (http:…
dhh authored
992 @attributes[attr_name] && [:text, :string].include?(column.send(:type)) && @attributes[attr_name].is_a?(String) && self.class.serialized_attributes[attr_name]
db045db @dhh Initial
dhh authored
993 end
994
995 # Returns the unserialized object of the attribute.
996 def unserialize_attribute(attr_name)
997 unserialized_object = object_from_yaml(@attributes[attr_name])
998
999 if unserialized_object.is_a?(self.class.serialized_attributes[attr_name])
1000 @attributes[attr_name] = unserialized_object
1001 else
1002 raise(
1003 SerializationTypeMismatch,
1004 "#{attr_name} was supposed to be a #{self.class.serialized_attributes[attr_name]}, " +
1005 "but was a #{unserialized_object.class.to_s}"
1006 )
1007 end
1008 end
1009
1010 # Updates the attribute identified by <tt>attr_name</tt> with the specified +value+. Empty strings for fixnum and float
1011 # columns are turned into nil.
1012 def write_attribute(attr_name, value) #:doc:
1013 @attributes[attr_name] = empty_string_for_number_column?(attr_name, value) ? nil : value
1014 end
1015
1016 def empty_string_for_number_column?(attr_name, value)
1017 column = column_for_attribute(attr_name)
1018 column && (column.klass == Fixnum || column.klass == Float) && value == ""
1019 end
1020
1021 def query_attribute(attr_name)
1022 attribute = @attributes[attr_name]
1023 if attribute.kind_of?(Fixnum) && attribute == 0
1024 false
1025 elsif attribute.kind_of?(String) && attribute == "0"
1026 false
1027 elsif attribute.kind_of?(String) && attribute.empty?
1028 false
1029 elsif attribute.nil?
1030 false
1031 elsif attribute == false
1032 false
1033 elsif attribute == "f"
1034 false
1035 elsif attribute == "false"
1036 false
1037 else
1038 true
1039 end
1040 end
1041
1042 def remove_attributes_protected_from_mass_assignment(attributes)
1043 if self.class.accessible_attributes.nil? && self.class.protected_attributes.nil?
1044 attributes.reject { |key, value| key == self.class.primary_key }
1045 elsif self.class.protected_attributes.nil?
1046 attributes.reject { |key, value| !self.class.accessible_attributes.include?(key.intern) || key == self.class.primary_key }
1047 elsif self.class.accessible_attributes.nil?
1048 attributes.reject { |key, value| self.class.protected_attributes.include?(key.intern) || key == self.class.primary_key }
1049 end
1050 end
1051
1052 # Returns copy of the attributes hash where all the values have been safely quoted for use in
1053 # an SQL statement.
9a248a8 @dhh Dont include the primary key in updates -- its unneeded and SQL Serve…
dhh authored
1054 def attributes_with_quotes(include_primary_key = true)
db045db @dhh Initial
dhh authored
1055 columns_hash = self.class.columns_hash
1056 @attributes.inject({}) do |attrs_quoted, pair|
9a248a8 @dhh Dont include the primary key in updates -- its unneeded and SQL Serve…
dhh authored
1057 attrs_quoted[pair.first] = quote(pair.last, columns_hash[pair.first]) unless !include_primary_key && pair.first == self.class.primary_key
db045db @dhh Initial
dhh authored
1058 attrs_quoted
1059 end
1060 end
1061
1062 # Quote strings appropriately for SQL statements.
1063 def quote(value, column = nil)
1064 connection.quote(value, column)
1065 end
1066
1067 # Interpolate custom sql string in instance context.
1068 # Optional record argument is meant for custom insert_sql.
1069 def interpolate_sql(sql, record = nil)
1070 instance_eval("%(#{sql})")
1071 end
1072
1073 # Initializes the attributes array with keys matching the columns from the linked table and
1074 # the values matching the corresponding default value of that column, so
1075 # that a new instance, or one populated from a passed-in Hash, still has all the attributes
1076 # that instances loaded from the database would.
1077 def attributes_from_column_definition
1078 connection.columns(self.class.table_name, "#{self.class.name} Columns").inject({}) do |attributes, column|
3e5a880 @dhh Switched strategy on the id_before_type_cast problem and just did an …
dhh authored
1079 attributes[column.name] = column.default unless column.name == self.class.primary_key
db045db @dhh Initial
dhh authored
1080 attributes
1081 end
1082 end
1083
1084 # Instantiates objects for all attribute classes that needs more than one constructor parameter. This is done
1085 # by calling new on the column type or aggregation type (through composed_of) object with these parameters.
1086 # So having the pairs written_on(1) = "2004", written_on(2) = "6", written_on(3) = "24", will instantiate
1087 # written_on (a date type) with Date.new("2004", "6", "24"). You can also specify a typecast character in the
1088 # parenteses to have the parameters typecasted before they're used in the constructor. Use i for Fixnum, f for Float,
1089 # s for String, and a for Array. If all the values for a given attribute is empty, the attribute will be set to nil.
1090 def assign_multiparameter_attributes(pairs)
1091 execute_callstack_for_multiparameter_attributes(
1092 extract_callstack_for_multiparameter_attributes(pairs)
1093 )
1094 end
1095
1096 # Includes an ugly hack for Time.local instead of Time.new because the latter is reserved by Time itself.
1097 def execute_callstack_for_multiparameter_attributes(callstack)
1098 callstack.each do |name, values|
1099 klass = (self.class.reflect_on_aggregation(name) || column_for_attribute(name)).klass
1100 if values.empty?
1101 send(name + "=", nil)
1102 else
1103 send(name + "=", Time == klass ? klass.local(*values) : klass.new(*values))
1104 end
1105 end
1106 end
1107
1108 def extract_callstack_for_multiparameter_attributes(pairs)
1109 attributes = { }
1110
1111 for pair in pairs
1112 multiparameter_name, value = pair
1113 attribute_name = multiparameter_name.split("(").first
1114 attributes[attribute_name] = [] unless attributes.include?(attribute_name)
1115
1116 unless value.empty?
1117 attributes[attribute_name] <<
1118 [find_parameter_position(multiparameter_name), type_cast_attribute_value(multiparameter_name, value)]
1119 end
1120 end
1121
1122 attributes.each { |name, values| attributes[name] = values.sort_by{ |v| v.first }.collect { |v| v.last } }
1123 end
1124
1125 def type_cast_attribute_value(multiparameter_name, value)
1126 multiparameter_name =~ /\([0-9]*([a-z])\)/ ? value.send("to_" + $1) : value
1127 end
1128
1129 def find_parameter_position(multiparameter_name)
1130 multiparameter_name.scan(/\(([0-9]*).*\)/).first.first
1131 end
1132
1133 # Returns a comma-separated pair list, like "key1 = val1, key2 = val2".
1134 def comma_pair_list(hash)
1135 hash.inject([]) { |list, pair| list << "#{pair.first} = #{pair.last}" }.join(", ")
1136 end
1137
1138 def quoted_column_names(attributes = attributes_with_quotes)
1139 attributes.keys.collect { |column_name| connection.quote_column_name(column_name) }
1140 end
1141
1142 def quote_columns(column_quoter, hash)
1143 hash.inject({}) {|list, pair|
1144 list[column_quoter.quote_column_name(pair.first)] = pair.last
1145 list
1146 }
1147 end
1148
1149 def quoted_comma_pair_list(column_quoter, hash)
1150 comma_pair_list(quote_columns(column_quoter, hash))
1151 end
1152
1153 def object_from_yaml(string)
1154 return string unless String === string
1155 if has_yaml_encoding_header?(string)
1156 begin
1157 YAML::load(string)
1158 rescue Object
1159 # Apparently wasn't YAML anyway
1160 string
1161 end
1162 else
1163 string
1164 end
1165 end
1166
1167 def has_yaml_encoding_header?(string)
1168 string[0..3] == "--- "
1169 end
1170 end
a775cb1 @dhh Added the option for sanitizing find_by_sql and the offset parts in r…
dhh authored
1171 end
Something went wrong with that request. Please try again.