Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

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