Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

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