Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100755 1373 lines (1210 sloc) 63.737 kb
db045db @dhh Initial
dhh authored
1 require 'yaml'
2
3 module ActiveRecord #:nodoc:
4 class ActiveRecordError < StandardError #:nodoc:
5 end
605bc77 @dhh Added a better exception for when a type column is used in a table wi…
dhh authored
6 class SubclassNotFound < ActiveRecordError #:nodoc:
7 end
db045db @dhh Initial
dhh authored
8 class AssociationTypeMismatch < ActiveRecordError #:nodoc:
9 end
10 class SerializationTypeMismatch < ActiveRecordError #:nodoc:
11 end
12 class AdapterNotSpecified < ActiveRecordError # :nodoc:
13 end
14 class AdapterNotFound < ActiveRecordError # :nodoc:
15 end
16 class ConnectionNotEstablished < ActiveRecordError #:nodoc:
17 end
18 class ConnectionFailed < ActiveRecordError #:nodoc:
19 end
20 class RecordNotFound < ActiveRecordError #:nodoc:
21 end
22 class StatementInvalid < ActiveRecordError #:nodoc:
23 end
554597d @dhh Added named bind-style variable interpolation #281 [Michael Koziarski]
dhh authored
24 class PreparedStatementInvalid < ActiveRecordError #:nodoc:
25 end
fbf9281 @dhh Added automated optimistic locking if the field lock_version is prese…
dhh authored
26 class StaleObjectError < ActiveRecordError #:nodoc:
27 end
db045db @dhh Initial
dhh authored
28
d2fefbe @dhh Added MultiparameterAssignmentErrors and AttributeAssignmentError exc…
dhh authored
29 class AttributeAssignmentError < ActiveRecordError #:nodoc:
30 attr_reader :exception, :attribute
31 def initialize(message, exception, attribute)
32 @exception = exception
33 @attribute = attribute
34 @message = message
35 end
36 end
37
38 class MultiparameterAssignmentErrors < ActiveRecordError #:nodoc:
39 attr_reader :errors
40 def initialize(errors)
41 @errors = errors
42 end
43 end
44
db045db @dhh Initial
dhh authored
45 # Active Record objects doesn't specify their attributes directly, but rather infer them from the table definition with
46 # which they're linked. Adding, removing, and changing attributes and their type is done directly in the database. Any change
47 # is instantly reflected in the Active Record objects. The mapping that binds a given Active Record class to a certain
48 # database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.
49 #
50 # See the mapping rules in table_name and the full example in link:files/README.html for more insight.
51 #
52 # == Creation
53 #
54 # Active Records accepts constructor parameters either in a hash or as a block. The hash method is especially useful when
55 # you're receiving the data from somewhere else, like a HTTP request. It works like this:
56 #
57 # user = User.new("name" => "David", "occupation" => "Code Artist")
58 # user.name # => "David"
59 #
60 # You can also use block initialization:
61 #
62 # user = User.new do |u|
63 # u.name = "David"
64 # u.occupation = "Code Artist"
65 # end
66 #
67 # And of course you can just create a bare object and specify the attributes after the fact:
68 #
69 # user = User.new
70 # user.name = "David"
71 # user.occupation = "Code Artist"
72 #
73 # == Conditions
74 #
75 # Conditions can either be specified as a string or an array representing the WHERE-part of an SQL statement.
76 # The array form is to be used when the condition input is tainted and requires sanitization. The string form can
77 # be used for statements that doesn't involve tainted data. Examples:
78 #
79 # User < ActiveRecord::Base
80 # def self.authenticate_unsafely(user_name, password)
81 # find_first("user_name = '#{user_name}' AND password = '#{password}'")
82 # end
83 #
84 # def self.authenticate_safely(user_name, password)
3e7d191 @dhh Added bind-style variable interpolation for the condition arrays that…
dhh authored
85 # find_first([ "user_name = ? AND password = ?", user_name, password ])
db045db @dhh Initial
dhh authored
86 # end
87 # end
88 #
2575b3b @dhh Added extra words of caution for guarding against SQL-injection attacks
dhh authored
89 # The <tt>authenticate_unsafely</tt> method inserts the parameters directly into the query and is thus susceptible to SQL-injection
90 # attacks if the <tt>user_name</tt> and +password+ parameters come directly from a HTTP request. The <tt>authenticate_safely</tt> method,
91 # on the other hand, will sanitize the <tt>user_name</tt> and +password+ before inserting them in the query, which will ensure that
db045db @dhh Initial
dhh authored
92 # an attacker can't escape the query and fake the login (or worse).
2575b3b @dhh Added extra words of caution for guarding against SQL-injection attacks
dhh authored
93 #
db045db @dhh Initial
dhh authored
94 # == Overwriting default accessors
95 #
96 # All column values are automatically available through basic accessors on the Active Record object, but some times you
97 # want to specialize this behavior. This can be done by either by overwriting the default accessors (using the same
98 # name as the attribute) calling read_attribute(attr_name) and write_attribute(attr_name, value) to actually change things.
99 # Example:
100 #
101 # class Song < ActiveRecord::Base
102 # # Uses an integer of seconds to hold the length of the song
103 #
104 # def length=(minutes)
105 # write_attribute("length", minutes * 60)
106 # end
107 #
108 # def length
109 # read_attribute("length") / 60
110 # end
111 # end
112 #
4eab375 @dhh Finished polishing API docs
dhh authored
113 # == Accessing attributes before they have been type casted
114 #
115 # Some times you want to be able to read the raw attribute data without having the column-determined type cast run its course first.
116 # That can be done by using the <attribute>_before_type_cast accessors that all attributes have. For example, if your Account model
117 # has a balance attribute, you can call account.balance_before_type_cast or account.id_before_type_cast.
118 #
119 # This is especially useful in validation situations where the user might supply a string for an integer field and you want to display
120 # the original string back in an error message. Accessing the attribute normally would type cast the string to 0, which isn't what you
121 # want.
122 #
ac8fd7d @dhh Added dynamic attribute-based finders as a cleaner way of getting obj…
dhh authored
123 # == Dynamic attribute-based finders
124 #
125 # Dynamic attribute-based finders are a cleaner way of getting objects by simple queries without turning to SQL. They work by
126 # appending the name of an attribute to <tt>find_by_</tt>, so you get finders like <tt>Person.find_by_user_name, Payment.find_by_transaction_id</tt>.
127 # So instead of writing <tt>Person.find_first(["user_name = ?", user_name])</tt>, you just do <tt>Person.find_by_user_name(user_name)</tt>.
128 #
129 # It's also possible to use multiple attributes in the same find by separating them with "_and_", so you get finders like
130 # <tt>Person.find_by_user_name_and_password</tt> or even <tt>Payment.find_by_purchaser_and_state_and_country</tt>. So instead of writing
131 # <tt>Person.find_first(["user_name = ? AND password = ?", user_name, password])</tt>, you just do
132 # <tt>Person.find_by_user_name_and_password(user_name, password)</tt>.
569f2ea @dhh Added the possibility of specifying the remaining options for find_fi…
dhh authored
133 #
134 # It's even possible to use all the additional parameters to find_first and find_all. For example, the full interface for Payment.find_all_by_amount
135 # is actually Payment.find_all_by_amount(amount, orderings = nil, limit = nil, joins = nil). And the full interface to Person.find_by_user_name is
136 # actually Person.find_by_user_name(user_name, orderings = nil)
959f362 @dhh Added find_all style to the new dynamic finders
dhh authored
137 #
098fa94 @dhh Fixed documentation snafus #575, #576, #577, #585
dhh authored
138 # == Saving arrays, hashes, and other non-mappable objects in text columns
db045db @dhh Initial
dhh authored
139 #
140 # 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+.
141 # This makes it possible to store arrays, hashes, and other non-mappeable objects without doing any additional work. Example:
142 #
143 # class User < ActiveRecord::Base
144 # serialize :preferences
145 # end
146 #
147 # user = User.create("preferences" => { "background" => "black", "display" => large })
148 # User.find(user.id).preferences # => { "background" => "black", "display" => large }
149 #
66f44e6 @dhh Updated documentation for serialize
dhh authored
150 # You can also specify an class option as the second parameter that'll raise an exception if a serialized object is retrieved as a
db045db @dhh Initial
dhh authored
151 # descendent of a class not in the hierarchy. Example:
152 #
153 # class User < ActiveRecord::Base
66f44e6 @dhh Updated documentation for serialize
dhh authored
154 # serialize :preferences, Hash
db045db @dhh Initial
dhh authored
155 # end
156 #
157 # user = User.create("preferences" => %w( one two three ))
158 # User.find(user.id).preferences # raises SerializationTypeMismatch
159 #
160 # == Single table inheritance
161 #
162 # Active Record allows inheritance by storing the name of the class in a column that by default is called "type" (can be changed
163 # by overwriting <tt>Base.inheritance_column</tt>). This means that an inheritance looking like this:
164 #
165 # class Company < ActiveRecord::Base; end
166 # class Firm < Company; end
167 # class Client < Company; end
168 # class PriorityClient < Client; end
169 #
e9426d2 @dhh Optimized the SQL used to generate has_and_belongs_to_many queries by…
dhh authored
170 # When you do Firm.create("name" => "37signals"), this record will be saved in the companies table with type = "Firm". You can then
db045db @dhh Initial
dhh authored
171 # fetch this row again using Company.find_first "name = '37signals'" and it will return a Firm object.
172 #
f033833 @dhh Improving documentation...
dhh authored
173 # 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
174 # like normal subclasses with no special magic for differentiating between them or reloading the right type with find.
175 #
db045db @dhh Initial
dhh authored
176 # Note, all the attributes for all the cases are kept in the same table. Read more:
177 # http://www.martinfowler.com/eaaCatalog/singleTableInheritance.html
178 #
179 # == Connection to multiple databases in different models
180 #
181 # Connections are usually created through ActiveRecord::Base.establish_connection and retrieved by ActiveRecord::Base.connection.
182 # All classes inheriting from ActiveRecord::Base will use this connection. But you can also set a class-specific connection.
183 # For example, if Course is a ActiveRecord::Base, but resides in a different database you can just say Course.establish_connection
184 # and Course *and all its subclasses* will use this connection instead.
185 #
186 # This feature is implemented by keeping a connection pool in ActiveRecord::Base that is a Hash indexed by the class. If a connection is
187 # requested, the retrieve_connection method will go up the class-hierarchy until a connection is found in the connection pool.
188 #
189 # == Exceptions
190 #
191 # * +ActiveRecordError+ -- generic error class and superclass of all other errors raised by Active Record
192 # * +AdapterNotSpecified+ -- the configuration hash used in <tt>establish_connection</tt> didn't include a
193 # <tt>:adapter</tt> key.
098fa94 @dhh Fixed documentation snafus #575, #576, #577, #585
dhh authored
194 # * +AdapterNotSpecified+ -- the <tt>:adapter</tt> key used in <tt>establish_connection</tt> specified an non-existent adapter
db045db @dhh Initial
dhh authored
195 # (or a bad spelling of an existing one).
196 # * +AssociationTypeMismatch+ -- the object assigned to the association wasn't of the type specified in the association definition.
66f44e6 @dhh Updated documentation for serialize
dhh authored
197 # * +SerializationTypeMismatch+ -- the object serialized wasn't of the class specified as the second parameter.
db045db @dhh Initial
dhh authored
198 # * +ConnectionNotEstablished+ -- no connection has been established. Use <tt>establish_connection</tt> before querying.
199 # * +RecordNotFound+ -- no record responded to the find* method.
200 # Either the row with the given ID doesn't exist or the row didn't meet the additional restrictions.
201 # * +StatementInvalid+ -- the database server rejected the SQL statement. The precise error is added in the message.
202 # Either the record with the given ID doesn't exist or the record didn't meet the additional restrictions.
d2fefbe @dhh Added MultiparameterAssignmentErrors and AttributeAssignmentError exc…
dhh authored
203 # * +MultiparameterAssignmentErrors+ -- collection of errors that occurred during a mass assignment using the
204 # +attributes=+ method. The +errors+ property of this exception contains an array of +AttributeAssignmentError+
205 # objects that should be inspected to determine which attributes triggered the errors.
206 # * +AttributeAssignmentError+ -- an error occurred while doing a mass assignment through the +attributes=+ method.
207 # You can inspect the +attribute+ property of the exception object to determine which attribute triggered the error.
db045db @dhh Initial
dhh authored
208 # *Note*: The attributes listed are class-level attributes (accessible from both the class and instance level).
209 # So it's possible to assign a logger to the class through Base.logger= which will then be used by all
210 # instances in the current object space.
211 class Base
212 include ClassInheritableAttributes
213
214 # Accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, which is then passed
215 # on to any new database connections made and which can be retrieved on both a class and instance level by calling +logger+.
216 cattr_accessor :logger
217
218 # Returns the connection currently associated with the class. This can
219 # also be used to "borrow" the connection to do database work unrelated
220 # to any of the specific Active Records.
221 def self.connection
222 retrieve_connection
223 end
224
225 # Returns the connection currently associated with the class. This can
226 # also be used to "borrow" the connection to do database work that isn't
227 # easily done without going straight to SQL.
228 def connection
229 self.class.connection
230 end
231
232 def self.inherited(child) #:nodoc:
233 @@subclasses[self] ||= []
234 @@subclasses[self] << child
235 super
236 end
237
238 @@subclasses = {}
8e1f1ee @dhh Moved require_association to associations.rb and added methods for re…
dhh authored
239
db045db @dhh Initial
dhh authored
240 cattr_accessor :configurations
241 @@primary_key_prefix_type = {}
242
243 # Accessor for the prefix type that will be prepended to every primary key column name. The options are :table_name and
244 # :table_name_with_underscore. If the first is specified, the Product class will look for "productid" instead of "id" as
245 # the primary column. If the latter is specified, the Product class will look for "product_id" instead of "id". Remember
246 # that this is a global setting for all Active Records.
247 cattr_accessor :primary_key_prefix_type
248 @@primary_key_prefix_type = nil
249
250 # Accessor for the name of the prefix string to prepend to every table name. So if set to "basecamp_", all
098fa94 @dhh Fixed documentation snafus #575, #576, #577, #585
dhh authored
251 # table names will be named like "basecamp_projects", "basecamp_people", etc. This is a convenient way of creating a namespace
db045db @dhh Initial
dhh authored
252 # for tables in a shared database. By default, the prefix is the empty string.
253 cattr_accessor :table_name_prefix
254 @@table_name_prefix = ""
255
256 # Works like +table_name_prefix+, but appends instead of prepends (set to "_basecamp" gives "projects_basecamp",
257 # "people_basecamp"). By default, the suffix is the empty string.
258 cattr_accessor :table_name_suffix
259 @@table_name_suffix = ""
260
261 # Indicate whether or not table names should be the pluralized versions of the corresponding class names.
262 # If true, this the default table name for a +Product+ class will be +products+. If false, it would just be +product+.
263 # See table_name for the full rules on table/class naming. This is true, by default.
264 cattr_accessor :pluralize_table_names
265 @@pluralize_table_names = true
266
911614d @dhh Added ActiveRecord::Base.colorize_logging to control whether to use c…
dhh authored
267 # Determines whether or not to use ANSI codes to colorize the logging statements committed by the connection adapter. These colors
268 # makes it much easier to overview things during debugging (when used through a reader like +tail+ and on a black background), but
269 # may complicate matters if you use software like syslog. This is true, by default.
270 cattr_accessor :colorize_logging
271 @@colorize_logging = true
272
60de8c1 @dhh Added Base.default_timezone accessor that determines whether to use T…
dhh authored
273 # Determines whether to use Time.local (using :local) or Time.utc (using :utc) when pulling dates and times from the database.
274 # This is set to :local by default.
275 cattr_accessor :default_timezone
276 @@default_timezone = :local
277
db045db @dhh Initial
dhh authored
278 class << self # Class methods
279 # Returns objects for the records responding to either a specific id (1), a list of ids (1, 5, 6) or an array of ids.
280 # If only one ID is specified, that object is returned directly. If more than one ID is specified, an array is returned.
281 # Examples:
282 # Person.find(1) # returns the object for ID = 1
283 # Person.find(1, 2, 6) # returns an array for objects with IDs in (1, 2, 6)
284 # Person.find([7, 17]) # returns an array for objects with IDs in (7, 17)
57ed93e @dhh Fixed that Base#find will return an array if given an array -- regard…
dhh authored
285 # Person.find([1]) # returns an array for objects the object with ID = 1
6bd672e @dhh Added that Base#find takes an optional options hash, including :condi…
dhh authored
286 #
287 # The last argument may be a Hash of find options. Currently, +conditions+ is the only option, behaving the same as with +find_all+.
569f2ea @dhh Added the possibility of specifying the remaining options for find_fi…
dhh authored
288 # Person.find(1, :conditions => "associate_id = 5"
289 # Person.find(1, 2, 6, :conditions => "status = 'active'"
290 # Person.find([7, 17], :conditions => ["sanitize_me = ?", "bare'quote"]
6bd672e @dhh Added that Base#find takes an optional options hash, including :condi…
dhh authored
291 #
db045db @dhh Initial
dhh authored
292 # +RecordNotFound+ is raised if no record can be found.
6bd672e @dhh Added that Base#find takes an optional options hash, including :condi…
dhh authored
293 def find(*args)
294 # Return an Array if ids are passed in an Array.
295 expects_array = args.first.kind_of?(Array)
296
297 # Extract options hash from argument list.
298 options = extract_options_from_args!(args)
299 conditions = " AND #{sanitize_sql(options[:conditions])}" if options[:conditions]
300
301 ids = args.flatten.compact.uniq
302 case ids.size
303
304 # Raise if no ids passed.
305 when 0
306 raise RecordNotFound, "Couldn't find #{name} without an ID#{conditions}"
307
308 # Find a single id.
309 when 1
310 unless result = find_first("#{primary_key} = #{sanitize(ids.first)}#{conditions}")
311 raise RecordNotFound, "Couldn't find #{name} with ID=#{ids.first}#{conditions}"
312 end
db045db @dhh Initial
dhh authored
313
6bd672e @dhh Added that Base#find takes an optional options hash, including :condi…
dhh authored
314 # Box result if expecting array.
315 expects_array ? [result] : result
db045db @dhh Initial
dhh authored
316
6bd672e @dhh Added that Base#find takes an optional options hash, including :condi…
dhh authored
317 # Find multiple ids.
db045db @dhh Initial
dhh authored
318 else
6bd672e @dhh Added that Base#find takes an optional options hash, including :condi…
dhh authored
319 ids_list = ids.map { |id| sanitize(id) }.join(',')
320 result = find_all("#{primary_key} IN (#{ids_list})#{conditions}", primary_key)
321 if result.size == ids.size
322 result
323 else
872ddaf @dhh Added bind-named arrays for interpolating a group of ids or strings i…
dhh authored
324 raise RecordNotFound, "Couldn't find all #{name.pluralize} with IDs (#{ids_list})#{conditions}"
6bd672e @dhh Added that Base#find takes an optional options hash, including :condi…
dhh authored
325 end
db045db @dhh Initial
dhh authored
326 end
327 end
328
2f94412 @dhh Added Base.exists?(id) that'll return true if an object of the class …
dhh authored
329 # Returns true if the given +id+ represents the primary key of a record in the database, false otherwise.
330 # Example:
331 # Person.exists?(5)
332 def exists?(id)
333 !find_first("#{primary_key} = #{sanitize(id)}").nil?
334 end
335
6bd672e @dhh Added that Base#find takes an optional options hash, including :condi…
dhh authored
336 # This method is deprecated in favor of find with the :conditions option.
db045db @dhh Initial
dhh authored
337 # Works like find, but the record matching +id+ must also meet the +conditions+.
338 # +RecordNotFound+ is raised if no record can be found matching the +id+ or meeting the condition.
339 # Example:
340 # Person.find_on_conditions 5, "first_name LIKE '%dav%' AND last_name = 'heinemeier'"
6bd672e @dhh Added that Base#find takes an optional options hash, including :condi…
dhh authored
341 def find_on_conditions(ids, conditions)
342 find(ids, :conditions => conditions)
db045db @dhh Initial
dhh authored
343 end
6bd672e @dhh Added that Base#find takes an optional options hash, including :condi…
dhh authored
344
db045db @dhh Initial
dhh authored
345 # Returns an array of all the objects that could be instantiated from the associated
346 # table in the database. The +conditions+ can be used to narrow the selection of objects (WHERE-part),
347 # such as by "color = 'red'", and arrangement of the selection can be done through +orderings+ (ORDER BY-part),
a775cb1 @dhh Added the option for sanitizing find_by_sql and the offset parts in r…
dhh authored
348 # such as by "last_name, first_name DESC". A maximum of returned objects and their offset can be specified in
349 # +limit+ (LIMIT...OFFSET-part). Examples:
db045db @dhh Initial
dhh authored
350 # Project.find_all "category = 'accounts'", "last_accessed DESC", 15
a775cb1 @dhh Added the option for sanitizing find_by_sql and the offset parts in r…
dhh authored
351 # Project.find_all ["category = ?", category_name], "created ASC", ["? OFFSET ?", 15, 20]
db045db @dhh Initial
dhh authored
352 def find_all(conditions = nil, orderings = nil, limit = nil, joins = nil)
353 sql = "SELECT * FROM #{table_name} "
354 sql << "#{joins} " if joins
355 add_conditions!(sql, conditions)
356 sql << "ORDER BY #{orderings} " unless orderings.nil?
4cd9c95 @dhh Added the possibility for adapters to overwrite add_limit! to impleme…
dhh authored
357
6bd672e @dhh Added that Base#find takes an optional options hash, including :condi…
dhh authored
358 connection.add_limit!(sql, sanitize_sql(limit)) unless limit.nil?
4cd9c95 @dhh Added the possibility for adapters to overwrite add_limit! to impleme…
dhh authored
359
db045db @dhh Initial
dhh authored
360 find_by_sql(sql)
361 end
362
a775cb1 @dhh Added the option for sanitizing find_by_sql and the offset parts in r…
dhh authored
363 # Works like find_all, but requires a complete SQL string. Examples:
db045db @dhh Initial
dhh authored
364 # Post.find_by_sql "SELECT p.*, c.author FROM posts p, comments c WHERE p.id = c.post_id"
a775cb1 @dhh Added the option for sanitizing find_by_sql and the offset parts in r…
dhh authored
365 # Post.find_by_sql ["SELECT * FROM posts WHERE author = ? AND created > ?", author_id, start_date]
db045db @dhh Initial
dhh authored
366 def find_by_sql(sql)
6bd672e @dhh Added that Base#find takes an optional options hash, including :condi…
dhh authored
367 connection.select_all(sanitize_sql(sql), "#{name} Load").inject([]) { |objects, record| objects << instantiate(record) }
db045db @dhh Initial
dhh authored
368 end
369
370 # Returns the object for the first record responding to the conditions in +conditions+,
371 # such as "group = 'master'". If more than one record is returned from the query, it's the first that'll
372 # be used to create the object. In such cases, it might be beneficial to also specify
373 # +orderings+, like "income DESC, name", to control exactly which record is to be used. Example:
374 # Employee.find_first "income > 50000", "income DESC, name"
375 def find_first(conditions = nil, orderings = nil)
6bd672e @dhh Added that Base#find takes an optional options hash, including :condi…
dhh authored
376 find_all(conditions, orderings, 1).first
db045db @dhh Initial
dhh authored
377 end
378
379 # Creates an object, instantly saves it as a record (if the validation permits it), and returns it. If the save
380 # fail under validations, the unsaved object is still returned.
381 def create(attributes = nil)
efa81da @dhh Added the option of supplying an array of ids and attributes to Base#…
dhh authored
382 if attributes.is_a?(Array)
383 attributes.collect { |attr| create(attr) }
384 else
385 object = new(attributes)
386 object.save
387 object
388 end
db045db @dhh Initial
dhh authored
389 end
390
391 # Finds the record from the passed +id+, instantly saves it with the passed +attributes+ (if the validation permits it),
392 # and returns it. If the save fail under validations, the unsaved object is still returned.
393 def update(id, attributes)
efa81da @dhh Added the option of supplying an array of ids and attributes to Base#…
dhh authored
394 if id.is_a?(Array)
395 idx = -1
396 id.collect { |id| idx += 1; update(id, attributes[idx]) }
397 else
398 object = find(id)
399 object.update_attributes(attributes)
400 object
401 end
db045db @dhh Initial
dhh authored
402 end
403
efa81da @dhh Added the option of supplying an array of ids and attributes to Base#…
dhh authored
404 # Deletes the record with the given +id+ without instantiating an object first. If an array of ids is provided, all of them
405 # are deleted.
648b8fd @dhh Added Base.destroy and Base.delete to remove records without holding …
dhh authored
406 def delete(id)
efa81da @dhh Added the option of supplying an array of ids and attributes to Base#…
dhh authored
407 delete_all([ "#{primary_key} IN (?)", id ])
648b8fd @dhh Added Base.destroy and Base.delete to remove records without holding …
dhh authored
408 end
409
410 # Destroys the record with the given +id+ by instantiating the object and calling #destroy (all the callbacks are the triggered).
efa81da @dhh Added the option of supplying an array of ids and attributes to Base#…
dhh authored
411 # If an array of ids is provided, all of them are destroyed.
648b8fd @dhh Added Base.destroy and Base.delete to remove records without holding …
dhh authored
412 def destroy(id)
efa81da @dhh Added the option of supplying an array of ids and attributes to Base#…
dhh authored
413 id.is_a?(Array) ? id.each { |id| destroy(id) } : find(id).destroy
648b8fd @dhh Added Base.destroy and Base.delete to remove records without holding …
dhh authored
414 end
415
69cb942 @dhh Changed the interface on AbstractAdapter to require that adapters ret…
dhh authored
416 # Updates all records with the SET-part of an SQL update statement in +updates+ and returns an integer with the number of rows updates.
417 # A subset of the records can be selected by specifying +conditions+. Example:
db045db @dhh Initial
dhh authored
418 # Billing.update_all "category = 'authorized', approved = 1", "author = 'David'"
419 def update_all(updates, conditions = nil)
566a369 @dhh Added that update_all calls sanitize_sql on its updates argument, so …
dhh authored
420 sql = "UPDATE #{table_name} SET #{sanitize_sql(updates)} "
db045db @dhh Initial
dhh authored
421 add_conditions!(sql, conditions)
69cb942 @dhh Changed the interface on AbstractAdapter to require that adapters ret…
dhh authored
422 return connection.update(sql, "#{name} Update")
db045db @dhh Initial
dhh authored
423 end
0d2db8a @dhh Added Base.update_collection that can update an array of id/attribute…
dhh authored
424
db045db @dhh Initial
dhh authored
425 # Destroys the objects for all the records that matches the +condition+ by instantiating each object and calling
426 # the destroy method. Example:
427 # Person.destroy_all "last_login < '2004-04-04'"
428 def destroy_all(conditions = nil)
429 find_all(conditions).each { |object| object.destroy }
430 end
431
432 # Deletes all the records that matches the +condition+ without instantiating the objects first (and hence not
433 # calling the destroy method). Example:
434 # Post.destroy_all "person_id = 5 AND (category = 'Something' OR category = 'Else')"
435 def delete_all(conditions = nil)
436 sql = "DELETE FROM #{table_name} "
437 add_conditions!(sql, conditions)
438 connection.delete(sql, "#{name} Delete all")
439 end
440
441 # Returns the number of records that meets the +conditions+. Zero is returned if no records match. Example:
442 # Product.count "sales > 1"
443 def count(conditions = nil)
444 sql = "SELECT COUNT(*) FROM #{table_name} "
445 add_conditions!(sql, conditions)
446 count_by_sql(sql)
447 end
448
449 # Returns the result of an SQL statement that should only include a COUNT(*) in the SELECT part.
450 # Product.count "SELECT COUNT(*) FROM sales s, customers c WHERE s.customer_id = c.id"
451 def count_by_sql(sql)
a775cb1 @dhh Added the option for sanitizing find_by_sql and the offset parts in r…
dhh authored
452 sql = sanitize_conditions(sql)
db045db @dhh Initial
dhh authored
453 count = connection.select_one(sql, "#{name} Count").values.first
454 return count ? count.to_i : 0
455 end
456
457 # Increments the specified counter by one. So <tt>DiscussionBoard.increment_counter("post_count",
458 # discussion_board_id)</tt> would increment the "post_count" counter on the board responding to discussion_board_id.
459 # This is used for caching aggregate values, so that they doesn't need to be computed every time. Especially important
460 # for looping over a collection where each element require a number of aggregate values. Like the DiscussionBoard
461 # that needs to list both the number of posts and comments.
462 def increment_counter(counter_name, id)
4940383 @dhh Fixed value quoting in all generated SQL statements, so that integers…
dhh authored
463 update_all "#{counter_name} = #{counter_name} + 1", "#{primary_key} = #{quote(id)}"
db045db @dhh Initial
dhh authored
464 end
465
466 # Works like increment_counter, but decrements instead.
467 def decrement_counter(counter_name, id)
4940383 @dhh Fixed value quoting in all generated SQL statements, so that integers…
dhh authored
468 update_all "#{counter_name} = #{counter_name} - 1", "#{primary_key} = #{quote(id)}"
db045db @dhh Initial
dhh authored
469 end
470
471 # Attributes named in this macro are protected from mass-assignment, such as <tt>new(attributes)</tt> and
472 # <tt>attributes=(attributes)</tt>. Their assignment will simply be ignored. Instead, you can use the direct writer
473 # methods to do assignment. This is meant to protect sensitive attributes to be overwritten by URL/form hackers. Example:
474 #
475 # class Customer < ActiveRecord::Base
476 # attr_protected :credit_rating
477 # end
478 #
479 # customer = Customer.new("name" => David, "credit_rating" => "Excellent")
480 # customer.credit_rating # => nil
481 # customer.attributes = { "description" => "Jolly fellow", "credit_rating" => "Superb" }
482 # customer.credit_rating # => nil
483 #
484 # customer.credit_rating = "Average"
485 # customer.credit_rating # => "Average"
486 def attr_protected(*attributes)
487 write_inheritable_array("attr_protected", attributes)
488 end
489
098fa94 @dhh Fixed documentation snafus #575, #576, #577, #585
dhh authored
490 # Returns an array of all the attributes that have been protected from mass-assignment.
db045db @dhh Initial
dhh authored
491 def protected_attributes # :nodoc:
492 read_inheritable_attribute("attr_protected")
493 end
494
495 # If this macro is used, only those attributed named in it will be accessible for mass-assignment, such as
496 # <tt>new(attributes)</tt> and <tt>attributes=(attributes)</tt>. This is the more conservative choice for mass-assignment
497 # protection. If you'd rather start from an all-open default and restrict attributes as needed, have a look at
498 # attr_protected.
499 def attr_accessible(*attributes)
500 write_inheritable_array("attr_accessible", attributes)
501 end
502
098fa94 @dhh Fixed documentation snafus #575, #576, #577, #585
dhh authored
503 # Returns an array of all the attributes that have been made accessible to mass-assignment.
db045db @dhh Initial
dhh authored
504 def accessible_attributes # :nodoc:
505 read_inheritable_attribute("attr_accessible")
506 end
507
508 # Specifies that the attribute by the name of +attr_name+ should be serialized before saving to the database and unserialized
509 # after loading from the database. The serialization is done through YAML. If +class_name+ is specified, the serialized
098fa94 @dhh Fixed documentation snafus #575, #576, #577, #585
dhh authored
510 # object must be of that class on retrieval or +SerializationTypeMismatch+ will be raised.
db045db @dhh Initial
dhh authored
511 def serialize(attr_name, class_name = Object)
512 write_inheritable_attribute("attr_serialized", serialized_attributes.update(attr_name.to_s => class_name))
513 end
514
515 # Returns a hash of all the attributes that have been specified for serialization as keys and their class restriction as values.
516 def serialized_attributes
517 read_inheritable_attribute("attr_serialized") || { }
518 end
519
520 # Guesses the table name (in forced lower-case) based on the name of the class in the inheritance hierarchy descending
521 # directly from ActiveRecord. So if the hierarchy looks like: Reply < Message < ActiveRecord, then Message is used
4eab375 @dhh Finished polishing API docs
dhh authored
522 # to guess the table name from even when called on Reply. The rules used to do the guess are handled by the Inflector class
523 # in Active Support, which knows almost all common English inflections (report a bug if your inflection isn't covered).
db045db @dhh Initial
dhh authored
524 #
525 # Additionally, the class-level table_name_prefix is prepended to the table_name and the table_name_suffix is appended.
526 # So if you have "myapp_" as a prefix, the table name guess for an Account class becomes "myapp_accounts".
527 #
528 # You can also overwrite this class method to allow for unguessable links, such as a Mouse class with a link to a
529 # "mice" table. Example:
530 #
531 # class Mouse < ActiveRecord::Base
9982578 @dhh Doc fix #805
dhh authored
532 # set_table_name "mice"
db045db @dhh Initial
dhh authored
533 # end
dcc4868 @dhh Fixed that Base.table_name would expect a parameter when used in has_…
dhh authored
534 def table_name
535 table_name_prefix + undecorated_table_name(class_name_of_active_record_descendant(self)) + table_name_suffix
db045db @dhh Initial
dhh authored
536 end
537
098fa94 @dhh Fixed documentation snafus #575, #576, #577, #585
dhh authored
538 # Defines the primary key field -- can be overridden in subclasses. Overwriting will negate any effect of the
db045db @dhh Initial
dhh authored
539 # primary_key_prefix_type setting, though.
540 def primary_key
541 case primary_key_prefix_type
542 when :table_name
543 Inflector.foreign_key(class_name_of_active_record_descendant(self), false)
544 when :table_name_with_underscore
545 Inflector.foreign_key(class_name_of_active_record_descendant(self))
546 else
547 "id"
548 end
549 end
550
551 # Defines the column name for use with single table inheritance -- can be overridden in subclasses.
552 def inheritance_column
553 "type"
554 end
555
1aa82b3 @dhh Added keyword-style approach to defining the custom relational bindin…
dhh authored
556 # Sets the table name to use to the given value, or (if the value
4eab375 @dhh Finished polishing API docs
dhh authored
557 # is nil or false) to the value returned by the given block.
1aa82b3 @dhh Added keyword-style approach to defining the custom relational bindin…
dhh authored
558 #
559 # Example:
560 #
561 # class Project < ActiveRecord::Base
562 # set_table_name "project"
563 # end
564 def set_table_name( value=nil, &block )
565 define_attr_method :table_name, value, &block
566 end
567 alias :table_name= :set_table_name
568
569 # Sets the name of the primary key column to use to the given value,
570 # or (if the value is nil or false) to the value returned by the given
4eab375 @dhh Finished polishing API docs
dhh authored
571 # block.
1aa82b3 @dhh Added keyword-style approach to defining the custom relational bindin…
dhh authored
572 #
573 # Example:
574 #
575 # class Project < ActiveRecord::Base
576 # set_primary_key "sysid"
577 # end
578 def set_primary_key( value=nil, &block )
579 define_attr_method :primary_key, value, &block
580 end
581 alias :primary_key= :set_primary_key
582
583 # Sets the name of the inheritance column to use to the given value,
584 # or (if the value # is nil or false) to the value returned by the
4eab375 @dhh Finished polishing API docs
dhh authored
585 # given block.
1aa82b3 @dhh Added keyword-style approach to defining the custom relational bindin…
dhh authored
586 #
587 # Example:
588 #
589 # class Project < ActiveRecord::Base
590 # set_inheritance_column do
591 # original_inheritance_column + "_id"
592 # end
593 # end
594 def set_inheritance_column( value=nil, &block )
595 define_attr_method :inheritance_column, value, &block
596 end
597 alias :inheritance_column= :set_inheritance_column
598
db045db @dhh Initial
dhh authored
599 # Turns the +table_name+ back into a class name following the reverse rules of +table_name+.
600 def class_name(table_name = table_name) # :nodoc:
601 # remove any prefix and/or suffix from the table name
602 class_name = Inflector.camelize(table_name[table_name_prefix.length..-(table_name_suffix.length + 1)])
603 class_name = Inflector.singularize(class_name) if pluralize_table_names
604 return class_name
605 end
606
607 # Returns an array of column objects for the table associated with this class.
608 def columns
609 @columns ||= connection.columns(table_name, "#{name} Columns")
610 end
611
612 # Returns an array of column objects for the table associated with this class.
613 def columns_hash
614 @columns_hash ||= columns.inject({}) { |hash, column| hash[column.name] = column; hash }
615 end
616
617 # Returns an array of columns objects where the primary id, all columns ending in "_id" or "_count",
618 # and columns used for single table inheritance has been removed.
619 def content_columns
620 @content_columns ||= columns.reject { |c| c.name == primary_key || c.name =~ /(_id|_count)$/ || c.name == inheritance_column }
621 end
622
623 # 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
624 # 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
625 # is available.
626 def column_methods_hash
627 @dynamic_methods_hash ||= columns_hash.keys.inject(Hash.new(false)) do |methods, attr|
628 methods[attr.to_sym] = true
629 methods["#{attr}=".to_sym] = true
630 methods["#{attr}?".to_sym] = true
dad37cf @dhh FormHelper should only use *_before_type_cast if they available on th…
dhh authored
631 methods["#{attr}_before_type_cast".to_sym] = true
db045db @dhh Initial
dhh authored
632 methods
633 end
634 end
1314f48 @dhh Added methods for resetting the cached information on classes that yo…
dhh authored
635
636 # Resets all the cached information about columns, which will cause they to be reloaded on the next request.
637 def reset_column_information
638 @columns = @columns_hash = @content_columns = @dynamic_methods_hash = nil
639 end
640
4eab375 @dhh Finished polishing API docs
dhh authored
641 def reset_column_information_and_inheritable_attributes_for_all_subclasses#:nodoc:
1314f48 @dhh Added methods for resetting the cached information on classes that yo…
dhh authored
642 subclasses.each { |klass| klass.reset_inheritable_attributes; klass.reset_column_information }
643 end
db045db @dhh Initial
dhh authored
644
645 # Transforms attribute key names into a more humane format, such as "First name" instead of "first_name". Example:
646 # Person.human_attribute_name("first_name") # => "First name"
4eab375 @dhh Finished polishing API docs
dhh authored
647 # Deprecated in favor of just calling "first_name".humanize
648 def human_attribute_name(attribute_key_name) #:nodoc:
1f7e72f @dhh Made human_attribute_name(attribute_key_name) use Inflector.humanize
dhh authored
649 attribute_key_name.humanize
db045db @dhh Initial
dhh authored
650 end
651
652 def descends_from_active_record? # :nodoc:
605bc77 @dhh Added a better exception for when a type column is used in a table wi…
dhh authored
653 superclass == Base || !columns_hash.has_key?(inheritance_column)
db045db @dhh Initial
dhh authored
654 end
655
4eab375 @dhh Finished polishing API docs
dhh authored
656 def quote(object) #:nodoc:
4940383 @dhh Fixed value quoting in all generated SQL statements, so that integers…
dhh authored
657 connection.quote(object)
658 end
659
660 # Used to sanitize objects before they're used in an SELECT SQL-statement. Delegates to <tt>connection.quote</tt>.
4eab375 @dhh Finished polishing API docs
dhh authored
661 def sanitize(object) #:nodoc:
4940383 @dhh Fixed value quoting in all generated SQL statements, so that integers…
dhh authored
662 connection.quote(object)
db045db @dhh Initial
dhh authored
663 end
664
665 # Used to aggregate logging and benchmark, so you can measure and represent multiple statements in a single block.
666 # Usage (hides all the SQL calls for the individual actions and calculates total runtime for them all):
667 #
668 # Project.benchmark("Creating project") do
669 # project = Project.create("name" => "stuff")
670 # project.create_manager("name" => "David")
671 # project.milestones << Milestone.find_all
672 # end
673 def benchmark(title)
674 result = nil
c00bf5f @dhh Fixed the verbosity of using the AR store
dhh authored
675 bm = Benchmark.measure { result = silence { yield } }
676 logger.info "#{title} (#{sprintf("%f", bm.real)})"
677 return result
678 end
679
680 # Silences the logger for the duration of the block.
681 def silence
682 result = nil
db045db @dhh Initial
dhh authored
683 logger.level = Logger::ERROR
c00bf5f @dhh Fixed the verbosity of using the AR store
dhh authored
684 result = yield
db045db @dhh Initial
dhh authored
685 logger.level = Logger::DEBUG
686 return result
687 end
688
97849de @dhh Fixed that association proxies would fail === tests like PremiumSubsc…
dhh authored
689 # Overwrite the default class equality method to provide support for association proxies.
690 def ===(object)
691 object.is_a?(self)
692 end
693
db045db @dhh Initial
dhh authored
694 private
695 # Finder methods must instantiate through this method to work with the single-table inheritance model
696 # that makes it possible to create objects of different types from the same table.
697 def instantiate(record)
605bc77 @dhh Added a better exception for when a type column is used in a table wi…
dhh authored
698 require_association_class(record[inheritance_column])
699
700 begin
701 object = record_with_type?(record) ? compute_type(record[inheritance_column]).allocate : allocate
702 rescue NameError
703 raise(
704 SubclassNotFound,
705 "The single-table inheritance mechanism failed to locate the subclass: '#{record[inheritance_column]}'. " +
706 "This error is raised because the column '#{inheritance_column}' is reserved for storing the class in case of inheritance. " +
707 "Please rename this column if you didn't intend it to be used for storing the inheritance class " +
708 "or overwrite #{self.to_s}.inheritance_column to use another column for that information."
709 )
710 end
711
db045db @dhh Initial
dhh authored
712 object.instance_variable_set("@attributes", record)
713 return object
714 end
715
716 # Returns true if the +record+ has a single table inheritance column and is using it.
717 def record_with_type?(record)
718 record.include?(inheritance_column) && !record[inheritance_column].nil? &&
719 !record[inheritance_column].empty?
720 end
721
722 # Returns the name of the type of the record using the current module as a prefix. So descendents of
723 # MyApp::Business::Account would be appear as "MyApp::Business::AccountSubclass".
724 def type_name_with_module(type_name)
725 self.name =~ /::/ ? self.name.scan(/(.*)::/).first.first + "::" + type_name : type_name
726 end
727
728 # Adds a sanitized version of +conditions+ to the +sql+ string. Note that it's the passed +sql+ string is changed.
729 def add_conditions!(sql, conditions)
6bd672e @dhh Added that Base#find takes an optional options hash, including :condi…
dhh authored
730 sql << "WHERE #{sanitize_sql(conditions)} " unless conditions.nil?
db045db @dhh Initial
dhh authored
731 sql << (conditions.nil? ? "WHERE " : " AND ") + type_condition unless descends_from_active_record?
732 end
733
734 def type_condition
735 " (" + subclasses.inject("#{inheritance_column} = '#{Inflector.demodulize(name)}' ") do |condition, subclass|
4940383 @dhh Fixed value quoting in all generated SQL statements, so that integers…
dhh authored
736 condition << "OR #{inheritance_column} = '#{Inflector.demodulize(subclass.name)}' "
db045db @dhh Initial
dhh authored
737 end + ") "
738 end
739
740 # Guesses the table name, but does not decorate it with prefix and suffix information.
741 def undecorated_table_name(class_name = class_name_of_active_record_descendant(self))
742 table_name = Inflector.underscore(Inflector.demodulize(class_name))
743 table_name = Inflector.pluralize(table_name) if pluralize_table_names
744 return table_name
745 end
746
ac8fd7d @dhh Added dynamic attribute-based finders as a cleaner way of getting obj…
dhh authored
747 # Enables dynamic finders like find_by_user_name(user_name) and find_by_user_name_and_password(user_name, password) that are turned into
959f362 @dhh Added find_all style to the new dynamic finders
dhh authored
748 # find_first(["user_name = ?", user_name]) and find_first(["user_name = ? AND password = ?", user_name, password]) respectively. Also works
749 # for find_all, but using find_all_by_amount(50) that are turned into find_all(["amount = ?", 50]).
569f2ea @dhh Added the possibility of specifying the remaining options for find_fi…
dhh authored
750 #
751 # It's even possible to use all the additional parameters to find_first and find_all. For example, the full interface for find_all_by_amount
752 # is actually find_all_by_amount(amount, orderings = nil, limit = nil, joins = nil).
ac8fd7d @dhh Added dynamic attribute-based finders as a cleaner way of getting obj…
dhh authored
753 def method_missing(method_id, *arguments)
754 method_name = method_id.id2name
755
06b8936 @dhh Fixed that find_by_* would fail when column names had numbers #670 [d…
dhh authored
756 if method_name =~ /find_(all_by|by)_([_a-z][_a-z\d]*)/
959f362 @dhh Added find_all style to the new dynamic finders
dhh authored
757 finder, attributes = ($1 == "all_by" ? :find_all : :find_first), $2.split("_and_")
ac8fd7d @dhh Added dynamic attribute-based finders as a cleaner way of getting obj…
dhh authored
758 attributes.each { |attr_name| super unless column_methods_hash[attr_name.intern] }
93ec130 @dhh Fixed that the dynamic finders didnt treat nil as a "IS NULL" but rat…
dhh authored
759
760 attr_index = -1
28edbca @dhh Fixed that the dynamic finder like find_all_by_something_boolean(fals…
dhh authored
761 conditions = attributes.collect { |attr_name| attr_index += 1; "#{attr_name} #{arguments[attr_index].nil? ? "IS" : "="} ? " }.join(" AND ")
569f2ea @dhh Added the possibility of specifying the remaining options for find_fi…
dhh authored
762 send(finder, [conditions, *arguments[0...attributes.length]], *arguments[attributes.length..-1])
ac8fd7d @dhh Added dynamic attribute-based finders as a cleaner way of getting obj…
dhh authored
763 else
764 super
765 end
766 end
db045db @dhh Initial
dhh authored
767
4eab375 @dhh Finished polishing API docs
dhh authored
768 # Defines an "attribute" method (like #inheritance_column or
769 # #table_name). A new (class) method will be created with the
770 # given name. If a value is specified, the new method will
771 # return that value (as a string). Otherwise, the given block
772 # will be used to compute the value of the method.
773 #
774 # The original method will be aliased, with the new name being
775 # prefixed with "original_". This allows the new method to
776 # access the original value.
777 #
778 # Example:
779 #
780 # class A < ActiveRecord::Base
781 # define_attr_method :primary_key, "sysid"
782 # define_attr_method( :inheritance_column ) do
783 # original_inheritance_column + "_id"
784 # end
785 # end
786 def define_attr_method(name, value=nil, &block)
787 sing = class << self; self; end
788 block = proc { value.to_s } if value
789 sing.send( :alias_method, "original_#{name}", name )
790 sing.send( :define_method, name, &block )
791 end
792
db045db @dhh Initial
dhh authored
793 protected
794 def subclasses
795 @@subclasses[self] ||= []
796 @@subclasses[self] + extra = @@subclasses[self].inject([]) {|list, subclass| list + subclass.subclasses }
797 end
798
799 # Returns the class type of the record using the current module as a prefix. So descendents of
800 # MyApp::Business::Account would be appear as MyApp::Business::AccountSubclass.
801 def compute_type(type_name)
802 type_name_with_module(type_name).split("::").inject(Object) do |final_type, part|
803 final_type = final_type.const_get(part)
804 end
805 end
806
807 # Returns the name of the class descending directly from ActiveRecord in the inheritance hierarchy.
808 def class_name_of_active_record_descendant(klass)
809 if klass.superclass == Base
810 return klass.name
811 elsif klass.superclass.nil?
812 raise ActiveRecordError, "#{name} doesn't belong in a hierarchy descending from ActiveRecord"
813 else
814 class_name_of_active_record_descendant(klass.superclass)
815 end
816 end
817
6bd672e @dhh Added that Base#find takes an optional options hash, including :condi…
dhh authored
818 # Accepts an array or string. The string is returned untouched, but the array has each value
819 # sanitized and interpolated into the sql statement.
820 # ["name='%s' and group_id='%s'", "foo'bar", 4] returns "name='foo''bar' and group_id='4'"
821 def sanitize_sql(ary)
822 return ary unless ary.is_a?(Array)
3e7d191 @dhh Added bind-style variable interpolation for the condition arrays that…
dhh authored
823
6bd672e @dhh Added that Base#find takes an optional options hash, including :condi…
dhh authored
824 statement, *values = ary
825 if values.first.is_a?(Hash) and statement =~ /:\w+/
826 replace_named_bind_variables(statement, values.first)
827 elsif statement.include?('?')
554597d @dhh Added named bind-style variable interpolation #281 [Michael Koziarski]
dhh authored
828 replace_bind_variables(statement, values)
829 else
4940383 @dhh Fixed value quoting in all generated SQL statements, so that integers…
dhh authored
830 statement % values.collect { |value| connection.quote_string(value.to_s) }
554597d @dhh Added named bind-style variable interpolation #281 [Michael Koziarski]
dhh authored
831 end
3e7d191 @dhh Added bind-style variable interpolation for the condition arrays that…
dhh authored
832 end
833
6bd672e @dhh Added that Base#find takes an optional options hash, including :condi…
dhh authored
834 alias_method :sanitize_conditions, :sanitize_sql
835
3e7d191 @dhh Added bind-style variable interpolation for the condition arrays that…
dhh authored
836 def replace_bind_variables(statement, values)
9322168 @dhh Restored bind arity checking #412 [bitsweat]
dhh authored
837 raise_if_bind_arity_mismatch(statement, statement.count('?'), values.size)
6bd672e @dhh Added that Base#find takes an optional options hash, including :condi…
dhh authored
838 bound = values.dup
872ddaf @dhh Added bind-named arrays for interpolating a group of ids or strings i…
dhh authored
839 statement.gsub('?') { quote_bound_value(bound.shift) }
554597d @dhh Added named bind-style variable interpolation #281 [Michael Koziarski]
dhh authored
840 end
841
6bd672e @dhh Added that Base#find takes an optional options hash, including :condi…
dhh authored
842 def replace_named_bind_variables(statement, bind_vars)
9322168 @dhh Restored bind arity checking #412 [bitsweat]
dhh authored
843 raise_if_bind_arity_mismatch(statement, statement.scan(/:(\w+)/).uniq.size, bind_vars.size)
6bd672e @dhh Added that Base#find takes an optional options hash, including :condi…
dhh authored
844 statement.gsub(/:(\w+)/) do
845 match = $1.to_sym
846 if bind_vars.has_key?(match)
872ddaf @dhh Added bind-named arrays for interpolating a group of ids or strings i…
dhh authored
847 quote_bound_value(bind_vars[match])
6bd672e @dhh Added that Base#find takes an optional options hash, including :condi…
dhh authored
848 else
849 raise PreparedStatementInvalid, "missing value for :#{match} in #{statement}"
554597d @dhh Added named bind-style variable interpolation #281 [Michael Koziarski]
dhh authored
850 end
851 end
9322168 @dhh Restored bind arity checking #412 [bitsweat]
dhh authored
852 end
853
872ddaf @dhh Added bind-named arrays for interpolating a group of ids or strings i…
dhh authored
854 def quote_bound_value(value)
855 case value
856 when Array
857 value.map { |v| connection.quote(v) }.join(',')
858 else
859 connection.quote(value)
860 end
861 end
862
9322168 @dhh Restored bind arity checking #412 [bitsweat]
dhh authored
863 def raise_if_bind_arity_mismatch(statement, expected, provided)
864 unless expected == provided
865 raise PreparedStatementInvalid, "wrong number of bind variables (#{provided} for #{expected}) in: #{statement}"
866 end
6bd672e @dhh Added that Base#find takes an optional options hash, including :condi…
dhh authored
867 end
554597d @dhh Added named bind-style variable interpolation #281 [Michael Koziarski]
dhh authored
868
6bd672e @dhh Added that Base#find takes an optional options hash, including :condi…
dhh authored
869 def extract_options_from_args!(args)
870 if args.last.is_a?(Hash) then args.pop else {} end
db045db @dhh Initial
dhh authored
871 end
aaf9a45 @dhh Added Base.validate_uniqueness thatv alidates whether the value of th…
dhh authored
872
873 def encode_quoted_value(value)
874 quoted_value = connection.quote(value)
875 quoted_value = "'#{quoted_value[1..-2].gsub(/\'/, "\\\\'")}'" if quoted_value.include?("\\\'")
876 quoted_value
877 end
db045db @dhh Initial
dhh authored
878 end
879
880 public
881 # New objects can be instantiated as either empty (pass no construction parameter) or pre-set with
882 # attributes but not yet saved (pass a hash with key names matching the associated table column names).
883 # In both instances, valid attribute keys are determined by the column names of the associated table --
884 # hence you can't have attributes that aren't part of the table columns.
885 def initialize(attributes = nil)
886 @attributes = attributes_from_column_definition
887 @new_record = true
888 ensure_proper_type
889 self.attributes = attributes unless attributes.nil?
890 yield self if block_given?
891 end
892
893 # Every Active Record class must use "id" as their primary ID. This getter overwrites the native
894 # id method, which isn't being used in this context.
895 def id
896 read_attribute(self.class.primary_key)
897 end
898
ce23862 @dhh Added alias_method :to_param, :id to Base, such that Active Record ob…
dhh authored
899 # Enables Active Record objects to be used as URL parameters in Action Pack automatically.
900 alias_method :to_param, :id
901
4eab375 @dhh Finished polishing API docs
dhh authored
902 def id_before_type_cast #:nodoc:
3e5a880 @dhh Switched strategy on the id_before_type_cast problem and just did an …
dhh authored
903 read_attribute_before_type_cast(self.class.primary_key)
904 end
905
4eab375 @dhh Finished polishing API docs
dhh authored
906 def quoted_id #:nodoc:
4940383 @dhh Fixed value quoting in all generated SQL statements, so that integers…
dhh authored
907 quote(id, self.class.columns_hash[self.class.primary_key])
908 end
909
db045db @dhh Initial
dhh authored
910 # Sets the primary ID.
911 def id=(value)
912 write_attribute(self.class.primary_key, value)
913 end
914
915 # Returns true if this object hasn't been saved yet -- that is, a record for the object doesn't exist yet.
916 def new_record?
917 @new_record
918 end
919
920 # * No record exists: Creates a new record with values matching those of the object attributes.
921 # * A record does exist: Updates the record with values matching those of the object attributes.
922 def save
923 create_or_update
924 end
925
926 # Deletes the record in the database and freezes this instance to reflect that no changes should
927 # be made (since they can't be persisted).
928 def destroy
929 unless new_record?
930 connection.delete(
931 "DELETE FROM #{self.class.table_name} " +
4940383 @dhh Fixed value quoting in all generated SQL statements, so that integers…
dhh authored
932 "WHERE #{self.class.primary_key} = #{quote(id)}",
db045db @dhh Initial
dhh authored
933 "#{self.class.name} Destroy"
934 )
935 end
936
937 freeze
938 end
939
940 # Returns a clone of the record that hasn't been assigned an id yet and is treated as a new record.
941 def clone
431e21c @dhh Fixed Base#clone for use with PostgreSQL #565 [hanson@surgery.wisc.edu]
dhh authored
942 attrs = self.attributes
a3298e5 @dhh Small indent
dhh authored
943 attrs.delete(self.class.primary_key)
431e21c @dhh Fixed Base#clone for use with PostgreSQL #565 [hanson@surgery.wisc.edu]
dhh authored
944 cloned_record = self.class.new(attrs)
db045db @dhh Initial
dhh authored
945 cloned_record
946 end
947
948 # Updates a single attribute and saves the record. This is especially useful for boolean flags on existing records.
d678997 @dhh Base#update_attribute isnt subject to validation
dhh authored
949 # Note: This method is overwritten by the Validation module that'll make sure that updates made with this method
950 # doesn't get subjected to validation checks. Hence, attributes can be updated even if the full object isn't valid.
db045db @dhh Initial
dhh authored
951 def update_attribute(name, value)
393e98a @dhh Fixed Base#update_attribute to be indifferent to whether a string or …
dhh authored
952 self[name] = value
d1abe80 @dhh Added Base#toggle(attribute) and Base#toggle!(attribute) that makes i…
dhh authored
953 save
604a094 @dhh Added Base#update_attributes that'll accept a hash of attributes and …
dhh authored
954 end
955
d678997 @dhh Base#update_attribute isnt subject to validation
dhh authored
956 # Updates all the attributes in from the passed hash and saves the record. If the object is invalid, the saving will
957 # fail and false will be returned.
604a094 @dhh Added Base#update_attributes that'll accept a hash of attributes and …
dhh authored
958 def update_attributes(attributes)
3bef4c2 @dhh Made Base#update_attributes actually work
dhh authored
959 self.attributes = attributes
604a094 @dhh Added Base#update_attributes that'll accept a hash of attributes and …
dhh authored
960 return save
db045db @dhh Initial
dhh authored
961 end
962
d1abe80 @dhh Added Base#toggle(attribute) and Base#toggle!(attribute) that makes i…
dhh authored
963 # Initializes the +attribute+ to zero if nil and adds one. Only makes sense for number-based attributes. Returns self.
964 def increment(attribute)
965 self[attribute] ||= 0
966 self[attribute] += 1
967 self
968 end
969
970 # Increments the +attribute+ and saves the record.
971 def increment!(attribute)
972 increment(attribute).update_attribute(attribute, self[attribute])
973 end
974
975 # Initializes the +attribute+ to zero if nil and subtracts one. Only makes sense for number-based attributes. Returns self.
976 def decrement(attribute)
977 self[attribute] ||= 0
978 self[attribute] -= 1
979 self
980 end
981
982 # Decrements the +attribute+ and saves the record.
983 def decrement!(attribute)
984 decrement(attribute).update_attribute(attribute, self[attribute])
985 end
986
987 # Turns an +attribute+ that's currently true into false and vice versa. Returns self.
988 def toggle(attribute)
989 self[attribute] = quote(!send("#{attribute}?", column_for_attribute(attribute)))
990 self
991 end
992
993 # Toggles the +attribute+ and saves the record.
994 def toggle!(attribute)
995 toggle(attribute).update_attribute(attribute, self[attribute])
996 end
997
3ff5c58 @dhh Added Base#reload that reloads the attributes of an object from the d…
dhh authored
998 # Reloads the attributes of this object from the database.
999 def reload
1000 clear_association_cache
1001 @attributes.update(self.class.find(self.id).instance_variable_get('@attributes'))
1002 return self
1003 end
1004
db045db @dhh Initial
dhh authored
1005 # Returns the value of attribute identified by <tt>attr_name</tt> after it has been type cast (for example,
1006 # "2004-12-12" in a data column is cast to a date object, like Date.new(2004, 12, 12)).
1007 # (Alias for the protected read_attribute method).
1008 def [](attr_name)
d1abe80 @dhh Added Base#toggle(attribute) and Base#toggle!(attribute) that makes i…
dhh authored
1009 read_attribute(attr_name.to_s)
db045db @dhh Initial
dhh authored
1010 end
1011
1012 # Updates the attribute identified by <tt>attr_name</tt> with the specified +value+.
1013 # (Alias for the protected write_attribute method).
1014 def []= (attr_name, value)
d1abe80 @dhh Added Base#toggle(attribute) and Base#toggle!(attribute) that makes i…
dhh authored
1015 write_attribute(attr_name.to_s, value)
db045db @dhh Initial
dhh authored
1016 end
1017
1018 # Allows you to set all the attributes at once by passing in a hash with keys
1019 # matching the attribute names (which again matches the column names). Sensitive attributes can be protected
1020 # from this form of mass-assignment by using the +attr_protected+ macro. Or you can alternatively
1021 # specify which attributes *can* be accessed in with the +attr_accessible+ macro. Then all the
1022 # attributes not included in that won't be allowed to be mass-assigned.
1023 def attributes=(attributes)
1024 return if attributes.nil?
2bfaa05 @dhh Fixed that symbols can be used on attribute assignment, like page.ema…
dhh authored
1025 attributes.stringify_keys!
db045db @dhh Initial
dhh authored
1026
1027 multi_parameter_attributes = []
1028 remove_attributes_protected_from_mass_assignment(attributes).each do |k, v|
1029 k.include?("(") ? multi_parameter_attributes << [ k, v ] : send(k + "=", v)
1030 end
1031 assign_multiparameter_attributes(multi_parameter_attributes)
1032 end
1033
b067bf7 @dhh Added Base#attributes that returns a hash of all the attributes with …
dhh authored
1034 # Returns a hash of all the attributes with their names as keys and clones of their objects as values.
1035 def attributes
1036 self.attribute_names.inject({}) do |attributes, name|
1037 begin
1038 attributes[name] = read_attribute(name).clone
1039 rescue TypeError
1040 attributes[name] = read_attribute(name)
1041 end
1042 attributes
1043 end
1044 end
1045
db045db @dhh Initial
dhh authored
1046 # Returns true if the specified +attribute+ has been set by the user or by a database load and is neither
1047 # nil nor empty? (the latter only applies to objects that responds to empty?, most notably Strings).
1048 def attribute_present?(attribute)
1049 is_empty = read_attribute(attribute).respond_to?("empty?") ? read_attribute(attribute).empty? : false
1050 @attributes.include?(attribute) && !@attributes[attribute].nil? && !is_empty
1051 end
1052
1053 # Returns an array of names for the attributes available on this object sorted alphabetically.
1054 def attribute_names
1055 @attributes.keys.sort
1056 end
1057
1058 # Returns the column object for the named attribute.
1059 def column_for_attribute(name)
d1abe80 @dhh Added Base#toggle(attribute) and Base#toggle!(attribute) that makes i…
dhh authored
1060 self.class.columns_hash[name.to_s]
db045db @dhh Initial
dhh authored
1061 end
1062
823554e @dhh Added support for associating unsaved objects #402 [Tim Bates]
dhh authored
1063 # Returns true if the +comparison_object+ is the same object, or is of the same type and has the same id.
db045db @dhh Initial
dhh authored
1064 def ==(comparison_object)
823554e @dhh Added support for associating unsaved objects #402 [Tim Bates]
dhh authored
1065 comparison_object.equal?(self) or (comparison_object.instance_of?(self.class) and comparison_object.id == id)
db045db @dhh Initial
dhh authored
1066 end
1067
1068 # Delegates to ==
1069 def eql?(comparison_object)
1070 self == (comparison_object)
1071 end
1072
1073 # Delegates to id in order to allow two records of the same type and id to work with something like:
1074 # [ Person.find(1), Person.find(2), Person.find(3) ] & [ Person.find(1), Person.find(4) ] # => [ Person.find(1) ]
1075 def hash
1076 id
1077 end
1078
1079 # For checking respond_to? without searching the attributes (which is faster).
1080 alias_method :respond_to_without_attributes?, :respond_to?
1081
1082 # A Person object with a name attribute can ask person.respond_to?("name"), person.respond_to?("name="), and
1083 # person.respond_to?("name?") which will all return true.
846f0d5 @dhh Fixed that the overwritten respond_to? method didn't take two paramet…
dhh authored
1084 def respond_to?(method, include_priv = false)
1085 self.class.column_methods_hash[method.to_sym] || respond_to_without_attributes?(method, include_priv)
db045db @dhh Initial
dhh authored
1086 end
d82f73e @dhh Abolished ActionController::Base.require_or_load in favor of require_…
dhh authored
1087
db045db @dhh Initial
dhh authored
1088 private
1089 def create_or_update
1090 if new_record? then create else update end
823554e @dhh Added support for associating unsaved objects #402 [Tim Bates]
dhh authored
1091 return true
db045db @dhh Initial
dhh authored
1092 end
1093
1094 # Updates the associated record with values matching those of the instant attributes.
1095 def update
1096 connection.update(
1097 "UPDATE #{self.class.table_name} " +
9a248a8 @dhh Dont include the primary key in updates -- its unneeded and SQL Serve…
dhh authored
1098 "SET #{quoted_comma_pair_list(connection, attributes_with_quotes(false))} " +
4940383 @dhh Fixed value quoting in all generated SQL statements, so that integers…
dhh authored
1099 "WHERE #{self.class.primary_key} = #{quote(id)}",
db045db @dhh Initial
dhh authored
1100 "#{self.class.name} Update"
1101 )
1102 end
1103
1104 # Creates a new record with values matching those of the instant attributes.
1105 def create
1106 self.id = connection.insert(
1107 "INSERT INTO #{self.class.table_name} " +
1108 "(#{quoted_column_names.join(', ')}) " +
1109 "VALUES(#{attributes_with_quotes.values.join(', ')})",
1110 "#{self.class.name} Create",
1111 self.class.primary_key, self.id
1112 )
1113
1114 @new_record = false
1115 end
1116
1117 # Sets the attribute used for single table inheritance to this class name if this is not the ActiveRecord descendant.
1118 # Considering the hierarchy Reply < Message < ActiveRecord, this makes it possible to do Reply.new without having to
1119 # set Reply[Reply.inheritance_column] = "Reply" yourself. No such attribute would be set for objects of the
1120 # Message class in that example.
1121 def ensure_proper_type
1122 unless self.class.descends_from_active_record?
1123 write_attribute(self.class.inheritance_column, Inflector.demodulize(self.class.name))
1124 end
1125 end
1126
1127 # Allows access to the object attributes, which are held in the @attributes hash, as were
1128 # they first-class methods. So a Person class with a name attribute can use Person#name and
1129 # Person#name= and never directly use the attributes hash -- except for multiple assigns with
1130 # ActiveRecord#attributes=. A Milestone class can also ask Milestone#completed? to test that
1131 # the completed attribute is not nil or 0.
1132 #
1133 # It's also possible to instantiate related objects, so a Client class belonging to the clients
1134 # table with a master_id foreign key can instantiate master through Client#master.
1135 def method_missing(method_id, *arguments)
1136 method_name = method_id.id2name
daf3e92 @dhh Added a db2 adapter that only depends on the Ruby/DB2 bindings (http:…
dhh authored
1137
db045db @dhh Initial
dhh authored
1138 if method_name =~ read_method? && @attributes.include?($1)
1139 return read_attribute($1)
7b5ed66 @dhh Added respondence to *_before_type_cast for all attributes to return …
dhh authored
1140 elsif method_name =~ read_untyped_method? && @attributes.include?($1)
1141 return read_attribute_before_type_cast($1)
db045db @dhh Initial
dhh authored
1142 elsif method_name =~ write_method? && @attributes.include?($1)
1143 write_attribute($1, arguments[0])
1144 elsif method_name =~ query_method? && @attributes.include?($1)
1145 return query_attribute($1)
1146 else
1147 super
1148 end
1149 end
1150
7b5ed66 @dhh Added respondence to *_before_type_cast for all attributes to return …
dhh authored
1151 def read_method?() /^([a-zA-Z][-_\w]*)[^=?]*$/ end
1152 def read_untyped_method?() /^([a-zA-Z][-_\w]*)_before_type_cast$/ end
1153 def write_method?() /^([a-zA-Z][-_\w]*)=.*$/ end
1154 def query_method?() /^([a-zA-Z][-_\w]*)\?$/ end
db045db @dhh Initial
dhh authored
1155
7b5ed66 @dhh Added respondence to *_before_type_cast for all attributes to return …
dhh authored
1156 # Returns the value of attribute identified by <tt>attr_name</tt> after it has been type cast (for example,
db045db @dhh Initial
dhh authored
1157 # "2004-12-12" in a data column is cast to a date object, like Date.new(2004, 12, 12)).
4eab375 @dhh Finished polishing API docs
dhh authored
1158 def read_attribute(attr_name)
db045db @dhh Initial
dhh authored
1159 if @attributes.keys.include? attr_name
1160 if column = column_for_attribute(attr_name)
7b5ed66 @dhh Added respondence to *_before_type_cast for all attributes to return …
dhh authored
1161 unserializable_attribute?(attr_name, column) ?
db045db @dhh Initial
dhh authored
1162 unserialize_attribute(attr_name) : column.type_cast(@attributes[attr_name])
7b5ed66 @dhh Added respondence to *_before_type_cast for all attributes to return …
dhh authored
1163 else
1164 @attributes[attr_name]
db045db @dhh Initial
dhh authored
1165 end
1166 else
1167 nil
1168 end
1169 end
1170
7b5ed66 @dhh Added respondence to *_before_type_cast for all attributes to return …
dhh authored
1171 def read_attribute_before_type_cast(attr_name)
1172 @attributes[attr_name]
1173 end
1174
db045db @dhh Initial
dhh authored
1175 # Returns true if the attribute is of a text column and marked for serialization.
1176 def unserializable_attribute?(attr_name, column)
daf3e92 @dhh Added a db2 adapter that only depends on the Ruby/DB2 bindings (http:…
dhh authored
1177 @attributes[attr_name] && [:text, :string].include?(column.send(:type)) && @attributes[attr_name].is_a?(String) && self.class.serialized_attributes[attr_name]
db045db @dhh Initial
dhh authored
1178 end
1179
1180 # Returns the unserialized object of the attribute.
1181 def unserialize_attribute(attr_name)
1182 unserialized_object = object_from_yaml(@attributes[attr_name])
1183
1184 if unserialized_object.is_a?(self.class.serialized_attributes[attr_name])
1185 @attributes[attr_name] = unserialized_object
1186 else
1187 raise(
1188 SerializationTypeMismatch,
1189 "#{attr_name} was supposed to be a #{self.class.serialized_attributes[attr_name]}, " +
1190 "but was a #{unserialized_object.class.to_s}"
1191 )
1192 end
1193 end
1194
1195 # Updates the attribute identified by <tt>attr_name</tt> with the specified +value+. Empty strings for fixnum and float
1196 # columns are turned into nil.
4eab375 @dhh Finished polishing API docs
dhh authored
1197 def write_attribute(attr_name, value)
db045db @dhh Initial
dhh authored
1198 @attributes[attr_name] = empty_string_for_number_column?(attr_name, value) ? nil : value
1199 end
1200
1201 def empty_string_for_number_column?(attr_name, value)
1202 column = column_for_attribute(attr_name)
1203 column && (column.klass == Fixnum || column.klass == Float) && value == ""
1204 end
1205
1206 def query_attribute(attr_name)
1207 attribute = @attributes[attr_name]
1208 if attribute.kind_of?(Fixnum) && attribute == 0
1209 false
1210 elsif attribute.kind_of?(String) && attribute == "0"
1211 false
1212 elsif attribute.kind_of?(String) && attribute.empty?
1213 false
1214 elsif attribute.nil?
1215 false
1216 elsif attribute == false
1217 false
1218 elsif attribute == "f"
1219 false
1220 elsif attribute == "false"
1221 false
1222 else
1223 true
1224 end
1225 end
1226
1227 def remove_attributes_protected_from_mass_assignment(attributes)
1228 if self.class.accessible_attributes.nil? && self.class.protected_attributes.nil?
95454bf @dhh Added mass-assignment protection for the inheritance column -- regard…
dhh authored
1229 attributes.reject { |key, value| attributes_protected_by_default.include?(key) }
db045db @dhh Initial
dhh authored
1230 elsif self.class.protected_attributes.nil?
95454bf @dhh Added mass-assignment protection for the inheritance column -- regard…
dhh authored
1231 attributes.reject { |key, value| !self.class.accessible_attributes.include?(key.intern) || attributes_protected_by_default.include?(key) }
db045db @dhh Initial
dhh authored
1232 elsif self.class.accessible_attributes.nil?
95454bf @dhh Added mass-assignment protection for the inheritance column -- regard…
dhh authored
1233 attributes.reject { |key, value| self.class.protected_attributes.include?(key.intern) || attributes_protected_by_default.include?(key) }
db045db @dhh Initial
dhh authored
1234 end
1235 end
1236
95454bf @dhh Added mass-assignment protection for the inheritance column -- regard…
dhh authored
1237 # The primary key and inheritance column can never be set by mass-assignment for security reasons.
1238 def attributes_protected_by_default
1239 [ self.class.primary_key, self.class.inheritance_column ]
1240 end
1241
db045db @dhh Initial
dhh authored
1242 # Returns copy of the attributes hash where all the values have been safely quoted for use in
1243 # an SQL statement.
9a248a8 @dhh Dont include the primary key in updates -- its unneeded and SQL Serve…
dhh authored
1244 def attributes_with_quotes(include_primary_key = true)
db045db @dhh Initial
dhh authored
1245 columns_hash = self.class.columns_hash
b29c01e @dhh Added that has_and_belongs_to_many associations with additional attri…
dhh authored
1246
dabf906 @dhh Added type conversion before saving a record, so string-based values …
dhh authored
1247 attrs_quoted = attributes.inject({}) do |attrs_quoted, pair|
9a248a8 @dhh Dont include the primary key in updates -- its unneeded and SQL Serve…
dhh authored
1248 attrs_quoted[pair.first] = quote(pair.last, columns_hash[pair.first]) unless !include_primary_key && pair.first == self.class.primary_key
db045db @dhh Initial
dhh authored
1249 attrs_quoted
1250 end
b29c01e @dhh Added that has_and_belongs_to_many associations with additional attri…
dhh authored
1251
1252 attrs_quoted.delete_if { |key, value| !self.class.columns_hash.keys.include?(key) }
db045db @dhh Initial
dhh authored
1253 end
1254
1255 # Quote strings appropriately for SQL statements.
1256 def quote(value, column = nil)
1257 connection.quote(value, column)
1258 end
1259
1260 # Interpolate custom sql string in instance context.
1261 # Optional record argument is meant for custom insert_sql.
1262 def interpolate_sql(sql, record = nil)
1263 instance_eval("%(#{sql})")
1264 end
1265
1266 # Initializes the attributes array with keys matching the columns from the linked table and
1267 # the values matching the corresponding default value of that column, so
1268 # that a new instance, or one populated from a passed-in Hash, still has all the attributes
1269 # that instances loaded from the database would.
1270 def attributes_from_column_definition
1271 connection.columns(self.class.table_name, "#{self.class.name} Columns").inject({}) do |attributes, column|
3e5a880 @dhh Switched strategy on the id_before_type_cast problem and just did an …
dhh authored
1272 attributes[column.name] = column.default unless column.name == self.class.primary_key
db045db @dhh Initial
dhh authored
1273 attributes
1274 end
1275 end
1276
1277 # Instantiates objects for all attribute classes that needs more than one constructor parameter. This is done
1278 # by calling new on the column type or aggregation type (through composed_of) object with these parameters.
1279 # So having the pairs written_on(1) = "2004", written_on(2) = "6", written_on(3) = "24", will instantiate
1280 # written_on (a date type) with Date.new("2004", "6", "24"). You can also specify a typecast character in the
098fa94 @dhh Fixed documentation snafus #575, #576, #577, #585
dhh authored
1281 # parentheses to have the parameters typecasted before they're used in the constructor. Use i for Fixnum, f for Float,
db045db @dhh Initial
dhh authored
1282 # s for String, and a for Array. If all the values for a given attribute is empty, the attribute will be set to nil.
1283 def assign_multiparameter_attributes(pairs)
1284 execute_callstack_for_multiparameter_attributes(
1285 extract_callstack_for_multiparameter_attributes(pairs)
1286 )
1287 end
1288
1289 # Includes an ugly hack for Time.local instead of Time.new because the latter is reserved by Time itself.
1290 def execute_callstack_for_multiparameter_attributes(callstack)
d2fefbe @dhh Added MultiparameterAssignmentErrors and AttributeAssignmentError exc…
dhh authored
1291 errors = []
db045db @dhh Initial
dhh authored
1292 callstack.each do |name, values|
1293 klass = (self.class.reflect_on_aggregation(name) || column_for_attribute(name)).klass
1294 if values.empty?
1295 send(name + "=", nil)
1296 else
d2fefbe @dhh Added MultiparameterAssignmentErrors and AttributeAssignmentError exc…
dhh authored
1297 begin
1298 send(name + "=", Time == klass ? klass.local(*values) : klass.new(*values))
1299 rescue => ex
1300 errors << AttributeAssignmentError.new("error on assignment #{values.inspect} to #{name}", ex, name)
1301 end
db045db @dhh Initial
dhh authored
1302 end
1303 end
d2fefbe @dhh Added MultiparameterAssignmentErrors and AttributeAssignmentError exc…
dhh authored
1304 unless errors.empty?
1305 raise MultiparameterAssignmentErrors.new(errors), "#{errors.size} error(s) on assignment of multiparameter attributes"
1306 end
db045db @dhh Initial
dhh authored
1307 end
1308
1309 def extract_callstack_for_multiparameter_attributes(pairs)
1310 attributes = { }
1311
1312 for pair in pairs
1313 multiparameter_name, value = pair
1314 attribute_name = multiparameter_name.split("(").first
1315 attributes[attribute_name] = [] unless attributes.include?(attribute_name)
1316
1317 unless value.empty?
1318 attributes[attribute_name] <<
b29c01e @dhh Added that has_and_belongs_to_many associations with additional attri…
dhh authored
1319 [ find_parameter_position(multiparameter_name), type_cast_attribute_value(multiparameter_name, value) ]
db045db @dhh Initial
dhh authored
1320 end
1321 end
1322
1323 attributes.each { |name, values| attributes[name] = values.sort_by{ |v| v.first }.collect { |v| v.last } }
1324 end
1325
1326 def type_cast_attribute_value(multiparameter_name, value)
1327 multiparameter_name =~ /\([0-9]*([a-z])\)/ ? value.send("to_" + $1) : value
1328 end
1329
1330 def find_parameter_position(multiparameter_name)
1331 multiparameter_name.scan(/\(([0-9]*).*\)/).first.first
1332 end
1333
1334 # Returns a comma-separated pair list, like "key1 = val1, key2 = val2".
1335 def comma_pair_list(hash)
1336 hash.inject([]) { |list, pair| list << "#{pair.first} = #{pair.last}" }.join(", ")
1337 end
1338
1339 def quoted_column_names(attributes = attributes_with_quotes)
1340 attributes.keys.collect { |column_name| connection.quote_column_name(column_name) }
1341 end
1342
1343 def quote_columns(column_quoter, hash)
b29c01e @dhh Added that has_and_belongs_to_many associations with additional attri…
dhh authored
1344 hash.inject({}) do |list, pair|
db045db @dhh Initial
dhh authored
1345 list[column_quoter.quote_column_name(pair.first)] = pair.last
1346 list
b29c01e @dhh Added that has_and_belongs_to_many associations with additional attri…
dhh authored
1347 end
db045db @dhh Initial
dhh authored
1348 end
1349
1350 def quoted_comma_pair_list(column_quoter, hash)
1351 comma_pair_list(quote_columns(column_quoter, hash))
1352 end
1353
1354 def object_from_yaml(string)
b40d3c9 @dhh Replaced === checks with is_a? checks #502, #82 [Marcel Molina]
dhh authored
1355 return string unless string.is_a?(String)
db045db @dhh Initial
dhh authored
1356 if has_yaml_encoding_header?(string)
1357 begin
1358 YAML::load(string)
1359 rescue Object
1360 # Apparently wasn't YAML anyway
1361 string
1362 end
1363 else
1364 string
1365 end
1366 end
1367
1368 def has_yaml_encoding_header?(string)
1369 string[0..3] == "--- "
1370 end
1371 end
1aa82b3 @dhh Added keyword-style approach to defining the custom relational bindin…
dhh authored
1372 end
Something went wrong with that request. Please try again.