Skip to content

HTTPS clone URL

Subversion checkout URL

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