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