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