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