Skip to content
This repository
Newer
Older
100755 1114 lines (976 sloc) 52.373 kb
db045dbb » dhh
2004-11-24 Initial
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
605bc775 » dhh
2004-12-14 Added a better exception for when a type column is used in a table wi…
9 class SubclassNotFound < ActiveRecordError #:nodoc:
10 end
db045dbb » dhh
2004-11-24 Initial
11 class AssociationTypeMismatch < ActiveRecordError #:nodoc:
12 end
13 class SerializationTypeMismatch < ActiveRecordError #:nodoc:
14 end
15 class AdapterNotSpecified < ActiveRecordError # :nodoc:
16 end
17 class AdapterNotFound < ActiveRecordError # :nodoc:
18 end
19 class ConnectionNotEstablished < ActiveRecordError #:nodoc:
20 end
21 class ConnectionFailed < ActiveRecordError #:nodoc:
22 end
23 class RecordNotFound < ActiveRecordError #:nodoc:
24 end
25 class StatementInvalid < ActiveRecordError #:nodoc:
26 end
554597d6 » dhh
2004-12-08 Added named bind-style variable interpolation #281 [Michael Koziarski]
27 class PreparedStatementInvalid < ActiveRecordError #:nodoc:
28 end
db045dbb » dhh
2004-11-24 Initial
29
30 # Active Record objects doesn't specify their attributes directly, but rather infer them from the table definition with
31 # which they're linked. Adding, removing, and changing attributes and their type is done directly in the database. Any change
32 # is instantly reflected in the Active Record objects. The mapping that binds a given Active Record class to a certain
33 # database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.
34 #
35 # See the mapping rules in table_name and the full example in link:files/README.html for more insight.
36 #
37 # == Creation
38 #
39 # Active Records accepts constructor parameters either in a hash or as a block. The hash method is especially useful when
40 # you're receiving the data from somewhere else, like a HTTP request. It works like this:
41 #
42 # user = User.new("name" => "David", "occupation" => "Code Artist")
43 # user.name # => "David"
44 #
45 # You can also use block initialization:
46 #
47 # user = User.new do |u|
48 # u.name = "David"
49 # u.occupation = "Code Artist"
50 # end
51 #
52 # And of course you can just create a bare object and specify the attributes after the fact:
53 #
54 # user = User.new
55 # user.name = "David"
56 # user.occupation = "Code Artist"
57 #
58 # == Conditions
59 #
60 # Conditions can either be specified as a string or an array representing the WHERE-part of an SQL statement.
61 # The array form is to be used when the condition input is tainted and requires sanitization. The string form can
62 # be used for statements that doesn't involve tainted data. Examples:
63 #
64 # User < ActiveRecord::Base
65 # def self.authenticate_unsafely(user_name, password)
66 # find_first("user_name = '#{user_name}' AND password = '#{password}'")
67 # end
68 #
69 # def self.authenticate_safely(user_name, password)
3e7d191e » dhh
2004-12-07 Added bind-style variable interpolation for the condition arrays that…
70 # find_first([ "user_name = ? AND password = ?", user_name, password ])
db045dbb » dhh
2004-11-24 Initial
71 # end
72 # end
73 #
2575b3b0 » dhh
2004-12-06 Added extra words of caution for guarding against SQL-injection attacks
74 # The <tt>authenticate_unsafely</tt> method inserts the parameters directly into the query and is thus susceptible to SQL-injection
75 # attacks if the <tt>user_name</tt> and +password+ parameters come directly from a HTTP request. The <tt>authenticate_safely</tt> method,
76 # on the other hand, will sanitize the <tt>user_name</tt> and +password+ before inserting them in the query, which will ensure that
db045dbb » dhh
2004-11-24 Initial
77 # an attacker can't escape the query and fake the login (or worse).
2575b3b0 » dhh
2004-12-06 Added extra words of caution for guarding against SQL-injection attacks
78 #
db045dbb » dhh
2004-11-24 Initial
79 # == Overwriting default accessors
80 #
81 # All column values are automatically available through basic accessors on the Active Record object, but some times you
82 # want to specialize this behavior. This can be done by either by overwriting the default accessors (using the same
83 # name as the attribute) calling read_attribute(attr_name) and write_attribute(attr_name, value) to actually change things.
84 # Example:
85 #
86 # class Song < ActiveRecord::Base
87 # # Uses an integer of seconds to hold the length of the song
88 #
89 # def length=(minutes)
90 # write_attribute("length", minutes * 60)
91 # end
92 #
93 # def length
94 # read_attribute("length") / 60
95 # end
96 # end
97 #
98 # == Saving arrays, hashes, and other non-mappeable objects in text columns
99 #
100 # Active Record can serialize any object in text columns using YAML. To do so, you must specify this with a call to the class method +serialize+.
101 # This makes it possible to store arrays, hashes, and other non-mappeable objects without doing any additional work. Example:
102 #
103 # class User < ActiveRecord::Base
104 # serialize :preferences
105 # end
106 #
107 # user = User.create("preferences" => { "background" => "black", "display" => large })
108 # User.find(user.id).preferences # => { "background" => "black", "display" => large }
109 #
110 # You can also specify an optional :class_name option that'll raise an exception if a serialized object is retrieved as a
111 # descendent of a class not in the hierarchy. Example:
112 #
113 # class User < ActiveRecord::Base
114 # serialize :preferences, :class_name => "Hash"
115 # end
116 #
117 # user = User.create("preferences" => %w( one two three ))
118 # User.find(user.id).preferences # raises SerializationTypeMismatch
119 #
120 # == Single table inheritance
121 #
122 # Active Record allows inheritance by storing the name of the class in a column that by default is called "type" (can be changed
123 # by overwriting <tt>Base.inheritance_column</tt>). This means that an inheritance looking like this:
124 #
125 # class Company < ActiveRecord::Base; end
126 # class Firm < Company; end
127 # class Client < Company; end
128 # class PriorityClient < Client; end
129 #
130 # When you do Firm.create("name" => "37signals"), this record with be saved in the companies table with type = "Firm". You can then
131 # fetch this row again using Company.find_first "name = '37signals'" and it will return a Firm object.
132 #
133 # Note, all the attributes for all the cases are kept in the same table. Read more:
134 # http://www.martinfowler.com/eaaCatalog/singleTableInheritance.html
135 #
136 # == Connection to multiple databases in different models
137 #
138 # Connections are usually created through ActiveRecord::Base.establish_connection and retrieved by ActiveRecord::Base.connection.
139 # All classes inheriting from ActiveRecord::Base will use this connection. But you can also set a class-specific connection.
140 # For example, if Course is a ActiveRecord::Base, but resides in a different database you can just say Course.establish_connection
141 # and Course *and all its subclasses* will use this connection instead.
142 #
143 # This feature is implemented by keeping a connection pool in ActiveRecord::Base that is a Hash indexed by the class. If a connection is
144 # requested, the retrieve_connection method will go up the class-hierarchy until a connection is found in the connection pool.
145 #
146 # == Exceptions
147 #
148 # * +ActiveRecordError+ -- generic error class and superclass of all other errors raised by Active Record
149 # * +AdapterNotSpecified+ -- the configuration hash used in <tt>establish_connection</tt> didn't include a
150 # <tt>:adapter</tt> key.
151 # * +AdapterNotSpecified+ -- the <tt>:adapter</tt> key used in <tt>establish_connection</tt> specified an unexisting adapter
152 # (or a bad spelling of an existing one).
153 # * +AssociationTypeMismatch+ -- the object assigned to the association wasn't of the type specified in the association definition.
154 # * +SerializationTypeMismatch+ -- the object serialized wasn't of the class specified in the <tt>:class_name</tt> option of
155 # the serialize definition.
156 # * +ConnectionNotEstablished+ -- no connection has been established. Use <tt>establish_connection</tt> before querying.
157 # * +RecordNotFound+ -- no record responded to the find* method.
158 # Either the row with the given ID doesn't exist or the row didn't meet the additional restrictions.
159 # * +StatementInvalid+ -- the database server rejected the SQL statement. The precise error is added in the message.
160 # Either the record with the given ID doesn't exist or the record didn't meet the additional restrictions.
161 #
162 # *Note*: The attributes listed are class-level attributes (accessible from both the class and instance level).
163 # So it's possible to assign a logger to the class through Base.logger= which will then be used by all
164 # instances in the current object space.
165 class Base
166 include ClassInheritableAttributes
167
168 # Accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, which is then passed
169 # on to any new database connections made and which can be retrieved on both a class and instance level by calling +logger+.
170 cattr_accessor :logger
171
172 # Returns the connection currently associated with the class. This can
173 # also be used to "borrow" the connection to do database work unrelated
174 # to any of the specific Active Records.
175 def self.connection
176 retrieve_connection
177 end
178
179 # Returns the connection currently associated with the class. This can
180 # also be used to "borrow" the connection to do database work that isn't
181 # easily done without going straight to SQL.
182 def connection
183 self.class.connection
184 end
185
186 def self.inherited(child) #:nodoc:
187 @@subclasses[self] ||= []
188 @@subclasses[self] << child
189 super
190 end
191
192 @@subclasses = {}
8e1f1ee4 » dhh
2004-12-12 Moved require_association to associations.rb and added methods for re…
193
db045dbb » dhh
2004-11-24 Initial
194 cattr_accessor :configurations
195 @@primary_key_prefix_type = {}
196
197 # Accessor for the prefix type that will be prepended to every primary key column name. The options are :table_name and
198 # :table_name_with_underscore. If the first is specified, the Product class will look for "productid" instead of "id" as
199 # the primary column. If the latter is specified, the Product class will look for "product_id" instead of "id". Remember
200 # that this is a global setting for all Active Records.
201 cattr_accessor :primary_key_prefix_type
202 @@primary_key_prefix_type = nil
203
204 # Accessor for the name of the prefix string to prepend to every table name. So if set to "basecamp_", all
205 # table names will be named like "basecamp_projects", "basecamp_people", etc. This is a convinient way of creating a namespace
206 # for tables in a shared database. By default, the prefix is the empty string.
207 cattr_accessor :table_name_prefix
208 @@table_name_prefix = ""
209
210 # Works like +table_name_prefix+, but appends instead of prepends (set to "_basecamp" gives "projects_basecamp",
211 # "people_basecamp"). By default, the suffix is the empty string.
212 cattr_accessor :table_name_suffix
213 @@table_name_suffix = ""
214
215 # Indicate whether or not table names should be the pluralized versions of the corresponding class names.
216 # If true, this the default table name for a +Product+ class will be +products+. If false, it would just be +product+.
217 # See table_name for the full rules on table/class naming. This is true, by default.
218 cattr_accessor :pluralize_table_names
219 @@pluralize_table_names = true
220
221 # When turned on (which is default), all associations are included using "load". This mean that any change is instant in cached
222 # environments like mod_ruby or FastCGI. When set to false, "require" is used, which is faster but requires server restart to
1314f48d » dhh
2004-12-12 Added methods for resetting the cached information on classes that yo…
223 # reflect changes.
db045dbb » dhh
2004-11-24 Initial
224 @@reload_associations = true
225 cattr_accessor :reload_associations
226
227 @@associations_loaded = []
228 cattr_accessor :associations_loaded
229
230 class << self # Class methods
231 # Returns objects for the records responding to either a specific id (1), a list of ids (1, 5, 6) or an array of ids.
232 # If only one ID is specified, that object is returned directly. If more than one ID is specified, an array is returned.
233 # Examples:
234 # Person.find(1) # returns the object for ID = 1
235 # Person.find(1, 2, 6) # returns an array for objects with IDs in (1, 2, 6)
236 # Person.find([7, 17]) # returns an array for objects with IDs in (7, 17)
57ed93ee » dhh
2004-12-15 Fixed that Base#find will return an array if given an array -- regard…
237 # Person.find([1]) # returns an array for objects the object with ID = 1
db045dbb » dhh
2004-11-24 Initial
238 # +RecordNotFound+ is raised if no record can be found.
239 def find(*ids)
57ed93ee » dhh
2004-12-15 Fixed that Base#find will return an array if given an array -- regard…
240 expects_array = ids.first.kind_of?(Array)
db045dbb » dhh
2004-11-24 Initial
241 ids = ids.flatten.compact.uniq
242
243 if ids.length > 1
49403831 » dhh
2004-12-07 Fixed value quoting in all generated SQL statements, so that integers…
244 ids_list = ids.map{ |id| "#{sanitize(id)}" }.join(", ")
db045dbb » dhh
2004-11-24 Initial
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
49403831 » dhh
2004-12-07 Fixed value quoting in all generated SQL statements, so that integers…
254 sql = "SELECT * FROM #{table_name} WHERE #{primary_key} = #{sanitize(id)}"
db045dbb » dhh
2004-11-24 Initial
255 sql << " AND #{type_condition}" unless descends_from_active_record?
256
257 if record = connection.select_one(sql, "#{name} Find")
57ed93ee » dhh
2004-12-15 Fixed that Base#find will return an array if given an array -- regard…
258 expects_array ? [instantiate(record)] : instantiate(record)
db045dbb » dhh
2004-11-24 Initial
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)
49403831 » dhh
2004-12-07 Fixed value quoting in all generated SQL statements, so that integers…
272 find_first("#{primary_key} = #{sanitize(id)} AND #{sanitize_conditions(conditions)}") ||
db045dbb » dhh
2004-11-24 Initial
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),
a775cb19 » dhh
2004-12-07 Added the option for sanitizing find_by_sql and the offset parts in r…
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:
db045dbb » dhh
2004-11-24 Initial
281 # Project.find_all "category = 'accounts'", "last_accessed DESC", 15
a775cb19 » dhh
2004-12-07 Added the option for sanitizing find_by_sql and the offset parts in r…
282 # Project.find_all ["category = ?", category_name], "created ASC", ["? OFFSET ?", 15, 20]
db045dbb » dhh
2004-11-24 Initial
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?
a775cb19 » dhh
2004-12-07 Added the option for sanitizing find_by_sql and the offset parts in r…
288 sql << "LIMIT #{sanitize_conditions(limit)} " unless limit.nil?
db045dbb » dhh
2004-11-24 Initial
289
290 find_by_sql(sql)
291 end
292
a775cb19 » dhh
2004-12-07 Added the option for sanitizing find_by_sql and the offset parts in r…
293 # Works like find_all, but requires a complete SQL string. Examples:
db045dbb » dhh
2004-11-24 Initial
294 # Post.find_by_sql "SELECT p.*, c.author FROM posts p, comments c WHERE p.id = c.post_id"
a775cb19 » dhh
2004-12-07 Added the option for sanitizing find_by_sql and the offset parts in r…
295 # Post.find_by_sql ["SELECT * FROM posts WHERE author = ? AND created > ?", author_id, start_date]
db045dbb » dhh
2004-11-24 Initial
296 def find_by_sql(sql)
a775cb19 » dhh
2004-12-07 Added the option for sanitizing find_by_sql and the offset parts in r…
297 sql = sanitize_conditions(sql)
db045dbb » dhh
2004-11-24 Initial
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)
a775cb19 » dhh
2004-12-07 Added the option for sanitizing find_by_sql and the offset parts in r…
369 sql = sanitize_conditions(sql)
db045dbb » dhh
2004-11-24 Initial
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)
49403831 » dhh
2004-12-07 Fixed value quoting in all generated SQL statements, so that integers…
380 update_all "#{counter_name} = #{counter_name} + 1", "#{primary_key} = #{quote(id)}"
db045dbb » dhh
2004-11-24 Initial
381 end
382
383 # Works like increment_counter, but decrements instead.
384 def decrement_counter(counter_name, id)
49403831 » dhh
2004-12-07 Fixed value quoting in all generated SQL statements, so that integers…
385 update_all "#{counter_name} = #{counter_name} - 1", "#{primary_key} = #{quote(id)}"
db045dbb » dhh
2004-11-24 Initial
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
1314f48d » dhh
2004-12-12 Added methods for resetting the cached information on classes that yo…
525
526 # Resets all the cached information about columns, which will cause they to be reloaded on the next request.
527 def reset_column_information
528 @columns = @columns_hash = @content_columns = @dynamic_methods_hash = nil
529 end
530
531 def reset_column_information_and_inheritable_attributes_for_all_subclasses
532 subclasses.each { |klass| klass.reset_inheritable_attributes; klass.reset_column_information }
533 end
db045dbb » dhh
2004-11-24 Initial
534
535 # Transforms attribute key names into a more humane format, such as "First name" instead of "first_name". Example:
536 # Person.human_attribute_name("first_name") # => "First name"
537 def human_attribute_name(attribute_key_name)
538 attribute_key_name.gsub(/_/, " ").capitalize unless attribute_key_name.nil?
539 end
540
541 def descends_from_active_record? # :nodoc:
605bc775 » dhh
2004-12-14 Added a better exception for when a type column is used in a table wi…
542 superclass == Base || !columns_hash.has_key?(inheritance_column)
db045dbb » dhh
2004-11-24 Initial
543 end
544
49403831 » dhh
2004-12-07 Fixed value quoting in all generated SQL statements, so that integers…
545 def quote(object)
546 connection.quote(object)
547 end
548
549 # Used to sanitize objects before they're used in an SELECT SQL-statement. Delegates to <tt>connection.quote</tt>.
db045dbb » dhh
2004-11-24 Initial
550 def sanitize(object) # :nodoc:
49403831 » dhh
2004-12-07 Fixed value quoting in all generated SQL statements, so that integers…
551 connection.quote(object)
db045dbb » dhh
2004-11-24 Initial
552 end
553
554 # Used to aggregate logging and benchmark, so you can measure and represent multiple statements in a single block.
555 # Usage (hides all the SQL calls for the individual actions and calculates total runtime for them all):
556 #
557 # Project.benchmark("Creating project") do
558 # project = Project.create("name" => "stuff")
559 # project.create_manager("name" => "David")
560 # project.milestones << Milestone.find_all
561 # end
562 def benchmark(title)
563 result = nil
564 logger.level = Logger::ERROR
565 bm = Benchmark.measure { result = yield }
566 logger.level = Logger::DEBUG
567 logger.info "#{title} (#{sprintf("%f", bm.real)})"
568 return result
569 end
570
571 private
572 # Finder methods must instantiate through this method to work with the single-table inheritance model
573 # that makes it possible to create objects of different types from the same table.
574 def instantiate(record)
605bc775 » dhh
2004-12-14 Added a better exception for when a type column is used in a table wi…
575 require_association_class(record[inheritance_column])
576
577 begin
578 object = record_with_type?(record) ? compute_type(record[inheritance_column]).allocate : allocate
579 rescue NameError
580 raise(
581 SubclassNotFound,
582 "The single-table inheritance mechanism failed to locate the subclass: '#{record[inheritance_column]}'. " +
583 "This error is raised because the column '#{inheritance_column}' is reserved for storing the class in case of inheritance. " +
584 "Please rename this column if you didn't intend it to be used for storing the inheritance class " +
585 "or overwrite #{self.to_s}.inheritance_column to use another column for that information."
586 )
587 end
588
db045dbb » dhh
2004-11-24 Initial
589 object.instance_variable_set("@attributes", record)
590 return object
591 end
592
593 # Returns true if the +record+ has a single table inheritance column and is using it.
594 def record_with_type?(record)
595 record.include?(inheritance_column) && !record[inheritance_column].nil? &&
596 !record[inheritance_column].empty?
597 end
598
599 # Returns the name of the type of the record using the current module as a prefix. So descendents of
600 # MyApp::Business::Account would be appear as "MyApp::Business::AccountSubclass".
601 def type_name_with_module(type_name)
602 self.name =~ /::/ ? self.name.scan(/(.*)::/).first.first + "::" + type_name : type_name
603 end
604
605 # Adds a sanitized version of +conditions+ to the +sql+ string. Note that it's the passed +sql+ string is changed.
606 def add_conditions!(sql, conditions)
607 sql << "WHERE #{sanitize_conditions(conditions)} " unless conditions.nil?
608 sql << (conditions.nil? ? "WHERE " : " AND ") + type_condition unless descends_from_active_record?
609 end
610
611 def type_condition
612 " (" + subclasses.inject("#{inheritance_column} = '#{Inflector.demodulize(name)}' ") do |condition, subclass|
49403831 » dhh
2004-12-07 Fixed value quoting in all generated SQL statements, so that integers…
613 condition << "OR #{inheritance_column} = '#{Inflector.demodulize(subclass.name)}' "
db045dbb » dhh
2004-11-24 Initial
614 end + ") "
615 end
616
617 # Guesses the table name, but does not decorate it with prefix and suffix information.
618 def undecorated_table_name(class_name = class_name_of_active_record_descendant(self))
619 table_name = Inflector.underscore(Inflector.demodulize(class_name))
620 table_name = Inflector.pluralize(table_name) if pluralize_table_names
621 return table_name
622 end
623
624
625 protected
626 def subclasses
627 @@subclasses[self] ||= []
628 @@subclasses[self] + extra = @@subclasses[self].inject([]) {|list, subclass| list + subclass.subclasses }
629 end
630
631 # Returns the class type of the record using the current module as a prefix. So descendents of
632 # MyApp::Business::Account would be appear as MyApp::Business::AccountSubclass.
633 def compute_type(type_name)
634 type_name_with_module(type_name).split("::").inject(Object) do |final_type, part|
635 final_type = final_type.const_get(part)
636 end
637 end
638
639 # Returns the name of the class descending directly from ActiveRecord in the inheritance hierarchy.
640 def class_name_of_active_record_descendant(klass)
641 if klass.superclass == Base
642 return klass.name
643 elsif klass.superclass.nil?
644 raise ActiveRecordError, "#{name} doesn't belong in a hierarchy descending from ActiveRecord"
645 else
646 class_name_of_active_record_descendant(klass.superclass)
647 end
648 end
649
650 # Accepts either a condition array or string. The string is returned untouched, but the array has each of
651 # the condition values sanitized.
652 def sanitize_conditions(conditions)
3e7d191e » dhh
2004-12-07 Added bind-style variable interpolation for the condition arrays that…
653 return conditions unless conditions.is_a?(Array)
654
554597d6 » dhh
2004-12-08 Added named bind-style variable interpolation #281 [Michael Koziarski]
655 statement, *values = conditions
3e7d191e » dhh
2004-12-07 Added bind-style variable interpolation for the condition arrays that…
656
554597d6 » dhh
2004-12-08 Added named bind-style variable interpolation #281 [Michael Koziarski]
657 if values[0].is_a?(Hash) && statement =~ /:\w+/
658 replace_named_bind_variables(statement, values[0])
659 elsif statement =~ /\?/
660 replace_bind_variables(statement, values)
661 else
49403831 » dhh
2004-12-07 Fixed value quoting in all generated SQL statements, so that integers…
662 statement % values.collect { |value| connection.quote_string(value.to_s) }
554597d6 » dhh
2004-12-08 Added named bind-style variable interpolation #281 [Michael Koziarski]
663 end
3e7d191e » dhh
2004-12-07 Added bind-style variable interpolation for the condition arrays that…
664 end
665
666 def replace_bind_variables(statement, values)
554597d6 » dhh
2004-12-08 Added named bind-style variable interpolation #281 [Michael Koziarski]
667 orig_statement = statement.clone
668 expected_number_of_variables = statement.count('?')
669 provided_number_of_variables = values.size
670
671 unless expected_number_of_variables == provided_number_of_variables
672 raise PreparedStatementInvalid, "wrong number of bind variables (#{provided_number_of_variables} for #{expected_number_of_variables})"
673 end
674
675 until values.empty?
aaf9a45c » dhh
2004-12-10 Added Base.validate_uniqueness thatv alidates whether the value of th…
676 statement.sub!(/\?/, encode_quoted_value(values.shift))
db045dbb » dhh
2004-11-24 Initial
677 end
554597d6 » dhh
2004-12-08 Added named bind-style variable interpolation #281 [Michael Koziarski]
678
679 statement.gsub('?') { |all, match| connection.quote(values.shift) }
680 end
681
682 def replace_named_bind_variables(statement, values_hash)
683 orig_statement = statement.clone
684 values_hash.keys.each do |k|
aaf9a45c » dhh
2004-12-10 Added Base.validate_uniqueness thatv alidates whether the value of th…
685 if statement.sub!(/:#{k.id2name}/, encode_quoted_value(values_hash.delete(k))).nil?
554597d6 » dhh
2004-12-08 Added named bind-style variable interpolation #281 [Michael Koziarski]
686 raise PreparedStatementInvalid, ":#{k} is not a variable in [#{orig_statement}]"
687 end
688 end
689
690 if statement =~ /(:\w+)/
691 raise PreparedStatementInvalid, "No value provided for #{$1} in [#{orig_statement}]"
692 end
693
694 return statement
db045dbb » dhh
2004-11-24 Initial
695 end
aaf9a45c » dhh
2004-12-10 Added Base.validate_uniqueness thatv alidates whether the value of th…
696
697 def encode_quoted_value(value)
698 quoted_value = connection.quote(value)
699 quoted_value = "'#{quoted_value[1..-2].gsub(/\'/, "\\\\'")}'" if quoted_value.include?("\\\'")
700 quoted_value
701 end
db045dbb » dhh
2004-11-24 Initial
702 end
703
704 public
705 # New objects can be instantiated as either empty (pass no construction parameter) or pre-set with
706 # attributes but not yet saved (pass a hash with key names matching the associated table column names).
707 # In both instances, valid attribute keys are determined by the column names of the associated table --
708 # hence you can't have attributes that aren't part of the table columns.
709 def initialize(attributes = nil)
710 @attributes = attributes_from_column_definition
711 @new_record = true
712 ensure_proper_type
713 self.attributes = attributes unless attributes.nil?
714 yield self if block_given?
715 end
716
717 # Every Active Record class must use "id" as their primary ID. This getter overwrites the native
718 # id method, which isn't being used in this context.
719 def id
720 read_attribute(self.class.primary_key)
721 end
722
49403831 » dhh
2004-12-07 Fixed value quoting in all generated SQL statements, so that integers…
723 def quoted_id
724 quote(id, self.class.columns_hash[self.class.primary_key])
725 end
726
db045dbb » dhh
2004-11-24 Initial
727 # Sets the primary ID.
728 def id=(value)
729 write_attribute(self.class.primary_key, value)
730 end
731
732 # Returns true if this object hasn't been saved yet -- that is, a record for the object doesn't exist yet.
733 def new_record?
734 @new_record
735 end
736
737 # * No record exists: Creates a new record with values matching those of the object attributes.
738 # * A record does exist: Updates the record with values matching those of the object attributes.
739 def save
740 create_or_update
741 return true
742 end
743
744 # Deletes the record in the database and freezes this instance to reflect that no changes should
745 # be made (since they can't be persisted).
746 def destroy
747 unless new_record?
748 connection.delete(
749 "DELETE FROM #{self.class.table_name} " +
49403831 » dhh
2004-12-07 Fixed value quoting in all generated SQL statements, so that integers…
750 "WHERE #{self.class.primary_key} = #{quote(id)}",
db045dbb » dhh
2004-11-24 Initial
751 "#{self.class.name} Destroy"
752 )
753 end
754
755 freeze
756 end
757
758 # Returns a clone of the record that hasn't been assigned an id yet and is treated as a new record.
759 def clone
760 attr = Hash.new
761
762 self.attribute_names.each do |name|
763 begin
764 attr[name] = read_attribute(name).clone
765 rescue TypeError
766 attr[name] = read_attribute(name)
767 end
768 end
769
770 cloned_record = self.class.new(attr)
771 cloned_record.instance_variable_set "@new_record", true
772 cloned_record.id = nil
773 cloned_record
774 end
775
776 # Updates a single attribute and saves the record. This is especially useful for boolean flags on existing records.
777 def update_attribute(name, value)
778 self[name] = value
779 save
780 end
781
782 # Returns the value of attribute identified by <tt>attr_name</tt> after it has been type cast (for example,
783 # "2004-12-12" in a data column is cast to a date object, like Date.new(2004, 12, 12)).
784 # (Alias for the protected read_attribute method).
785 def [](attr_name)
786 read_attribute(attr_name)
787 end
788
789 # Updates the attribute identified by <tt>attr_name</tt> with the specified +value+.
790 # (Alias for the protected write_attribute method).
791 def []= (attr_name, value)
792 write_attribute(attr_name, value)
793 end
794
795 # Allows you to set all the attributes at once by passing in a hash with keys
796 # matching the attribute names (which again matches the column names). Sensitive attributes can be protected
797 # from this form of mass-assignment by using the +attr_protected+ macro. Or you can alternatively
798 # specify which attributes *can* be accessed in with the +attr_accessible+ macro. Then all the
799 # attributes not included in that won't be allowed to be mass-assigned.
800 def attributes=(attributes)
801 return if attributes.nil?
802
803 multi_parameter_attributes = []
804 remove_attributes_protected_from_mass_assignment(attributes).each do |k, v|
805 k.include?("(") ? multi_parameter_attributes << [ k, v ] : send(k + "=", v)
806 end
807 assign_multiparameter_attributes(multi_parameter_attributes)
808 end
809
810 # Returns true if the specified +attribute+ has been set by the user or by a database load and is neither
811 # nil nor empty? (the latter only applies to objects that responds to empty?, most notably Strings).
812 def attribute_present?(attribute)
813 is_empty = read_attribute(attribute).respond_to?("empty?") ? read_attribute(attribute).empty? : false
814 @attributes.include?(attribute) && !@attributes[attribute].nil? && !is_empty
815 end
816
817 # Returns an array of names for the attributes available on this object sorted alphabetically.
818 def attribute_names
819 @attributes.keys.sort
820 end
821
822 # Returns the column object for the named attribute.
823 def column_for_attribute(name)
824 self.class.columns_hash[name]
825 end
826
827 # Returns true if the +comparison_object+ is of the same type and has the same id.
828 def ==(comparison_object)
829 comparison_object.instance_of?(self.class) && comparison_object.id == id
830 end
831
832 # Delegates to ==
833 def eql?(comparison_object)
834 self == (comparison_object)
835 end
836
837 # Delegates to id in order to allow two records of the same type and id to work with something like:
838 # [ Person.find(1), Person.find(2), Person.find(3) ] & [ Person.find(1), Person.find(4) ] # => [ Person.find(1) ]
839 def hash
840 id
841 end
842
843 # For checking respond_to? without searching the attributes (which is faster).
844 alias_method :respond_to_without_attributes?, :respond_to?
845
846 # A Person object with a name attribute can ask person.respond_to?("name"), person.respond_to?("name="), and
847 # person.respond_to?("name?") which will all return true.
848 def respond_to?(method)
849 self.class.column_methods_hash[method.to_sym] || respond_to_without_attributes?(method)
850 end
d82f73ec » dhh
2004-11-30 Abolished ActionController::Base.require_or_load in favor of require_…
851
db045dbb » dhh
2004-11-24 Initial
852 private
853 def create_or_update
854 if new_record? then create else update end
855 end
856
857 # Updates the associated record with values matching those of the instant attributes.
858 def update
859 connection.update(
860 "UPDATE #{self.class.table_name} " +
9a248a83 » dhh
2004-12-01 Dont include the primary key in updates -- its unneeded and SQL Serve…
861 "SET #{quoted_comma_pair_list(connection, attributes_with_quotes(false))} " +
49403831 » dhh
2004-12-07 Fixed value quoting in all generated SQL statements, so that integers…
862 "WHERE #{self.class.primary_key} = #{quote(id)}",
db045dbb » dhh
2004-11-24 Initial
863 "#{self.class.name} Update"
864 )
865 end
866
867 # Creates a new record with values matching those of the instant attributes.
868 def create
869 self.id = connection.insert(
870 "INSERT INTO #{self.class.table_name} " +
871 "(#{quoted_column_names.join(', ')}) " +
872 "VALUES(#{attributes_with_quotes.values.join(', ')})",
873 "#{self.class.name} Create",
874 self.class.primary_key, self.id
875 )
876
877 @new_record = false
878 end
879
880 # Sets the attribute used for single table inheritance to this class name if this is not the ActiveRecord descendant.
881 # Considering the hierarchy Reply < Message < ActiveRecord, this makes it possible to do Reply.new without having to
882 # set Reply[Reply.inheritance_column] = "Reply" yourself. No such attribute would be set for objects of the
883 # Message class in that example.
884 def ensure_proper_type
885 unless self.class.descends_from_active_record?
886 write_attribute(self.class.inheritance_column, Inflector.demodulize(self.class.name))
887 end
888 end
889
890 # Allows access to the object attributes, which are held in the @attributes hash, as were
891 # they first-class methods. So a Person class with a name attribute can use Person#name and
892 # Person#name= and never directly use the attributes hash -- except for multiple assigns with
893 # ActiveRecord#attributes=. A Milestone class can also ask Milestone#completed? to test that
894 # the completed attribute is not nil or 0.
895 #
896 # It's also possible to instantiate related objects, so a Client class belonging to the clients
897 # table with a master_id foreign key can instantiate master through Client#master.
898 def method_missing(method_id, *arguments)
899 method_name = method_id.id2name
900
901
902
903 if method_name =~ read_method? && @attributes.include?($1)
904 return read_attribute($1)
905 elsif method_name =~ write_method? && @attributes.include?($1)
906 write_attribute($1, arguments[0])
907 elsif method_name =~ query_method? && @attributes.include?($1)
908 return query_attribute($1)
909 else
910 super
911 end
912 end
913
914 def read_method?() /^([a-zA-Z][-_\w]*)[^=?]*$/ end
915 def write_method?() /^([a-zA-Z][-_\w]*)=.*$/ end
916 def query_method?() /^([a-zA-Z][-_\w]*)\?$/ end
917
918 # Returns the value of attribute identified by <tt>attr_name</tt> after it has been type cast (for example,
919 # "2004-12-12" in a data column is cast to a date object, like Date.new(2004, 12, 12)).
920 def read_attribute(attr_name) #:doc:
921 if @attributes.keys.include? attr_name
922 if column = column_for_attribute(attr_name)
923 @attributes[attr_name] = unserializable_attribute?(attr_name, column) ?
924 unserialize_attribute(attr_name) : column.type_cast(@attributes[attr_name])
925 end
926
927 @attributes[attr_name]
928 else
929 nil
930 end
931 end
932
933 # Returns true if the attribute is of a text column and marked for serialization.
934 def unserializable_attribute?(attr_name, column)
935 @attributes[attr_name] && column.send(:type) == :text && @attributes[attr_name].is_a?(String) && self.class.serialized_attributes[attr_name]
936 end
937
938 # Returns the unserialized object of the attribute.
939 def unserialize_attribute(attr_name)
940 unserialized_object = object_from_yaml(@attributes[attr_name])
941
942 if unserialized_object.is_a?(self.class.serialized_attributes[attr_name])
943 @attributes[attr_name] = unserialized_object
944 else
945 raise(
946 SerializationTypeMismatch,
947 "#{attr_name} was supposed to be a #{self.class.serialized_attributes[attr_name]}, " +
948 "but was a #{unserialized_object.class.to_s}"
949 )
950 end
951 end
952
953 # Updates the attribute identified by <tt>attr_name</tt> with the specified +value+. Empty strings for fixnum and float
954 # columns are turned into nil.
955 def write_attribute(attr_name, value) #:doc:
956 @attributes[attr_name] = empty_string_for_number_column?(attr_name, value) ? nil : value
957 end
958
959 def empty_string_for_number_column?(attr_name, value)
960 column = column_for_attribute(attr_name)
961 column && (column.klass == Fixnum || column.klass == Float) && value == ""
962 end
963
964 def query_attribute(attr_name)
965 attribute = @attributes[attr_name]
966 if attribute.kind_of?(Fixnum) && attribute == 0
967 false
968 elsif attribute.kind_of?(String) && attribute == "0"
969 false
970 elsif attribute.kind_of?(String) && attribute.empty?
971 false
972 elsif attribute.nil?
973 false
974 elsif attribute == false
975 false
976 elsif attribute == "f"
977 false
978 elsif attribute == "false"
979 false
980 else
981 true
982 end
983 end
984
985 def remove_attributes_protected_from_mass_assignment(attributes)
986 if self.class.accessible_attributes.nil? && self.class.protected_attributes.nil?
987 attributes.reject { |key, value| key == self.class.primary_key }
988 elsif self.class.protected_attributes.nil?
989 attributes.reject { |key, value| !self.class.accessible_attributes.include?(key.intern) || key == self.class.primary_key }
990 elsif self.class.accessible_attributes.nil?
991 attributes.reject { |key, value| self.class.protected_attributes.include?(key.intern) || key == self.class.primary_key }
992 end
993 end
994
995 # Returns copy of the attributes hash where all the values have been safely quoted for use in
996 # an SQL statement.
9a248a83 » dhh
2004-12-01 Dont include the primary key in updates -- its unneeded and SQL Serve…
997 def attributes_with_quotes(include_primary_key = true)
db045dbb » dhh
2004-11-24 Initial
998 columns_hash = self.class.columns_hash
999 @attributes.inject({}) do |attrs_quoted, pair|
9a248a83 » dhh
2004-12-01 Dont include the primary key in updates -- its unneeded and SQL Serve…
1000 attrs_quoted[pair.first] = quote(pair.last, columns_hash[pair.first]) unless !include_primary_key && pair.first == self.class.primary_key
db045dbb » dhh
2004-11-24 Initial
1001 attrs_quoted
1002 end
1003 end
1004
1005 # Quote strings appropriately for SQL statements.
1006 def quote(value, column = nil)
1007 connection.quote(value, column)
1008 end
1009
1010 # Interpolate custom sql string in instance context.
1011 # Optional record argument is meant for custom insert_sql.
1012 def interpolate_sql(sql, record = nil)
1013 instance_eval("%(#{sql})")
1014 end
1015
1016 # Initializes the attributes array with keys matching the columns from the linked table and
1017 # the values matching the corresponding default value of that column, so
1018 # that a new instance, or one populated from a passed-in Hash, still has all the attributes
1019 # that instances loaded from the database would.
1020 def attributes_from_column_definition
1021 connection.columns(self.class.table_name, "#{self.class.name} Columns").inject({}) do |attributes, column|
1022 attributes[column.name] = column.default unless column.name == self.class.primary_key
1023 attributes
1024 end
1025 end
1026
1027 # Instantiates objects for all attribute classes that needs more than one constructor parameter. This is done
1028 # by calling new on the column type or aggregation type (through composed_of) object with these parameters.
1029 # So having the pairs written_on(1) = "2004", written_on(2) = "6", written_on(3) = "24", will instantiate
1030 # written_on (a date type) with Date.new("2004", "6", "24"). You can also specify a typecast character in the
1031 # parenteses to have the parameters typecasted before they're used in the constructor. Use i for Fixnum, f for Float,
1032 # s for String, and a for Array. If all the values for a given attribute is empty, the attribute will be set to nil.
1033 def assign_multiparameter_attributes(pairs)
1034 execute_callstack_for_multiparameter_attributes(
1035 extract_callstack_for_multiparameter_attributes(pairs)
1036 )
1037 end
1038
1039 # Includes an ugly hack for Time.local instead of Time.new because the latter is reserved by Time itself.
1040 def execute_callstack_for_multiparameter_attributes(callstack)
1041 callstack.each do |name, values|
1042 klass = (self.class.reflect_on_aggregation(name) || column_for_attribute(name)).klass
1043 if values.empty?
1044 send(name + "=", nil)
1045 else
1046 send(name + "=", Time == klass ? klass.local(*values) : klass.new(*values))
1047 end
1048 end
1049 end
1050
1051 def extract_callstack_for_multiparameter_attributes(pairs)
1052 attributes = { }
1053
1054 for pair in pairs
1055 multiparameter_name, value = pair
1056 attribute_name = multiparameter_name.split("(").first
1057 attributes[attribute_name] = [] unless attributes.include?(attribute_name)
1058
1059 unless value.empty?
1060 attributes[attribute_name] <<
1061 [find_parameter_position(multiparameter_name), type_cast_attribute_value(multiparameter_name, value)]
1062 end
1063 end
1064
1065 attributes.each { |name, values| attributes[name] = values.sort_by{ |v| v.first }.collect { |v| v.last } }
1066 end
1067
1068 def type_cast_attribute_value(multiparameter_name, value)
1069 multiparameter_name =~ /\([0-9]*([a-z])\)/ ? value.send("to_" + $1) : value
1070 end
1071
1072 def find_parameter_position(multiparameter_name)
1073 multiparameter_name.scan(/\(([0-9]*).*\)/).first.first
1074 end
1075
1076 # Returns a comma-separated pair list, like "key1 = val1, key2 = val2".
1077 def comma_pair_list(hash)
1078 hash.inject([]) { |list, pair| list << "#{pair.first} = #{pair.last}" }.join(", ")
1079 end
1080
1081 def quoted_column_names(attributes = attributes_with_quotes)
1082 attributes.keys.collect { |column_name| connection.quote_column_name(column_name) }
1083 end
1084
1085 def quote_columns(column_quoter, hash)
1086 hash.inject({}) {|list, pair|
1087 list[column_quoter.quote_column_name(pair.first)] = pair.last
1088 list
1089 }
1090 end
1091
1092 def quoted_comma_pair_list(column_quoter, hash)
1093 comma_pair_list(quote_columns(column_quoter, hash))
1094 end
1095
1096 def object_from_yaml(string)
1097 return string unless String === string
1098 if has_yaml_encoding_header?(string)
1099 begin
1100 YAML::load(string)
1101 rescue Object
1102 # Apparently wasn't YAML anyway
1103 string
1104 end
1105 else
1106 string
1107 end
1108 end
1109
1110 def has_yaml_encoding_header?(string)
1111 string[0..3] == "--- "
1112 end
1113 end
a775cb19 » dhh
2004-12-07 Added the option for sanitizing find_by_sql and the offset parts in r…
1114 end
Something went wrong with that request. Please try again.