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