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