Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

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