bmaland-has_many_polymorphs 2.5.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,27 @@
1
+
2
+ require 'active_record'
3
+
4
+ RAILS_DEFAULT_LOGGER = nil unless defined? RAILS_DEFAULT_LOGGER
5
+
6
+ require 'has_many_polymorphs/reflection'
7
+ require 'has_many_polymorphs/association'
8
+ require 'has_many_polymorphs/class_methods'
9
+
10
+ require 'has_many_polymorphs/support_methods'
11
+ require 'has_many_polymorphs/base'
12
+
13
+ class ActiveRecord::Base
14
+ extend ActiveRecord::Associations::PolymorphicClassMethods
15
+ end
16
+
17
+ if ENV['HMP_DEBUG'] || ENV['RAILS_ENV'] =~ /development|test/ && ENV['USER'] == 'eweaver'
18
+ require 'has_many_polymorphs/debugging_tools'
19
+ end
20
+
21
+ if defined? Rails and RAILS_ENV and RAILS_ROOT
22
+ _logger_warn "rails environment detected"
23
+ # require 'has_many_polymorphs/configuration'
24
+ require 'has_many_polymorphs/autoload'
25
+ end
26
+
27
+ _logger_debug "loaded ok"
@@ -0,0 +1,160 @@
1
+ module ActiveRecord #:nodoc:
2
+ module Associations #:nodoc:
3
+
4
+ class PolymorphicError < ActiveRecordError #:nodoc:
5
+ end
6
+
7
+ class PolymorphicMethodNotSupportedError < ActiveRecordError #:nodoc:
8
+ end
9
+
10
+ # The association class for a <tt>has_many_polymorphs</tt> association.
11
+ class PolymorphicAssociation < HasManyThroughAssociation
12
+
13
+ # Push a record onto the association. Triggers a database load for a uniqueness check only if <tt>:skip_duplicates</tt> is <tt>true</tt>. Return value is undefined.
14
+ def <<(*records)
15
+ return if records.empty?
16
+
17
+ if @reflection.options[:skip_duplicates]
18
+ _logger_debug "Loading instances for polymorphic duplicate push check; use :skip_duplicates => false and perhaps a database constraint to avoid this possible performance issue"
19
+ load_target
20
+ end
21
+
22
+ @reflection.klass.transaction do
23
+ flatten_deeper(records).each do |record|
24
+ if @owner.new_record? or not record.respond_to?(:new_record?) or record.new_record?
25
+ raise PolymorphicError, "You can't associate unsaved records."
26
+ end
27
+ next if @reflection.options[:skip_duplicates] and @target.include? record
28
+ @owner.send(@reflection.through_reflection.name).proxy_target << @reflection.klass.create!(construct_join_attributes(record))
29
+ @target << record if loaded?
30
+ end
31
+ end
32
+
33
+ self
34
+ end
35
+
36
+ alias :push :<<
37
+ alias :concat :<<
38
+
39
+ # Runs a <tt>find</tt> against the association contents, returning the matched records. All regular <tt>find</tt> options except <tt>:include</tt> are supported.
40
+ def find(*args)
41
+ opts = args._extract_options!
42
+ opts.delete :include
43
+ super(*(args + [opts]))
44
+ end
45
+
46
+ def construct_scope
47
+ _logger_warn "Warning; not all usage scenarios for polymorphic scopes are supported yet."
48
+ super
49
+ end
50
+
51
+ # Deletes a record from the association. Return value is undefined.
52
+ def delete(*records)
53
+ records = flatten_deeper(records)
54
+ records.reject! {|record| @target.delete(record) if record.new_record?}
55
+ return if records.empty?
56
+
57
+ @reflection.klass.transaction do
58
+ records.each do |record|
59
+ joins = @reflection.through_reflection.name
60
+ @owner.send(joins).delete(@owner.send(joins).select do |join|
61
+ join.send(@reflection.options[:polymorphic_key]) == record.id and
62
+ join.send(@reflection.options[:polymorphic_type_key]) == "#{record.class.base_class}"
63
+ end)
64
+ @target.delete(record)
65
+ end
66
+ end
67
+ end
68
+
69
+ # Clears all records from the association. Returns an empty array.
70
+ def clear(klass = nil)
71
+ load_target
72
+ return if @target.empty?
73
+
74
+ if klass
75
+ delete(@target.select {|r| r.is_a? klass })
76
+ else
77
+ @owner.send(@reflection.through_reflection.name).clear
78
+ @target.clear
79
+ end
80
+ []
81
+ end
82
+
83
+ protected
84
+
85
+ # undef :sum
86
+ # undef :create!
87
+
88
+ def construct_quoted_owner_attributes(*args) #:nodoc:
89
+ # no access to returning() here? why not?
90
+ type_key = @reflection.options[:foreign_type_key]
91
+ h = {@reflection.primary_key_name => @owner.id}
92
+ h[type_key] = @owner.class.base_class.name if type_key
93
+ h
94
+ end
95
+
96
+ def construct_from #:nodoc:
97
+ # build the FROM part of the query, in this case, the polymorphic join table
98
+ @reflection.klass.quoted_table_name
99
+ end
100
+
101
+ def construct_owner #:nodoc:
102
+ # the table name for the owner object's class
103
+ @owner.class.quoted_table_name
104
+ end
105
+
106
+ def construct_owner_key #:nodoc:
107
+ # the primary key field for the owner object
108
+ @owner.class.primary_key
109
+ end
110
+
111
+ def construct_select(custom_select = nil) #:nodoc:
112
+ # build the select query
113
+ selected = custom_select || @reflection.options[:select]
114
+ end
115
+
116
+ def construct_joins(custom_joins = nil) #:nodoc:
117
+ # build the string of default joins
118
+ "JOIN #{construct_owner} AS polymorphic_parent ON #{construct_from}.#{@reflection.options[:foreign_key]} = polymorphic_parent.#{construct_owner_key} " +
119
+ @reflection.options[:from].map do |plural|
120
+ klass = plural._as_class
121
+ "LEFT JOIN #{klass.quoted_table_name} ON #{construct_from}.#{@reflection.options[:polymorphic_key]} = #{klass.quoted_table_name}.#{klass.primary_key} AND #{construct_from}.#{@reflection.options[:polymorphic_type_key]} = #{@reflection.klass.quote_value(klass.base_class.name)}"
122
+ end.uniq.join(" ") + " #{custom_joins}"
123
+ end
124
+
125
+ def construct_conditions #:nodoc:
126
+ # build the fully realized condition string
127
+ conditions = construct_quoted_owner_attributes.map do |field, value|
128
+ "#{construct_from}.#{field} = #{@reflection.klass.quote_value(value)}" if value
129
+ end
130
+ conditions << custom_conditions if custom_conditions
131
+ "(" + conditions.compact.join(') AND (') + ")"
132
+ end
133
+
134
+ def custom_conditions #:nodoc:
135
+ # custom conditions... not as messy as has_many :through because our joins are a little smarter
136
+ if @reflection.options[:conditions]
137
+ "(" + interpolate_sql(@reflection.klass.send(:sanitize_sql, @reflection.options[:conditions])) + ")"
138
+ end
139
+ end
140
+
141
+ alias :construct_owner_attributes :construct_quoted_owner_attributes
142
+ alias :conditions :custom_conditions # XXX possibly not necessary
143
+ alias :sql_conditions :custom_conditions # XXX ditto
144
+
145
+ # construct attributes for join for a particular record
146
+ def construct_join_attributes(record) #:nodoc:
147
+ {@reflection.options[:polymorphic_key] => record.id,
148
+ @reflection.options[:polymorphic_type_key] => "#{record.class.base_class}",
149
+ @reflection.options[:foreign_key] => @owner.id}.merge(@reflection.options[:foreign_type_key] ?
150
+ {@reflection.options[:foreign_type_key] => "#{@owner.class.base_class}"} : {}) # for double-sided relationships
151
+ end
152
+
153
+ def build(attrs = nil) #:nodoc:
154
+ raise PolymorphicMethodNotSupportedError, "You can't associate new records."
155
+ end
156
+
157
+ end
158
+
159
+ end
160
+ end
@@ -0,0 +1,74 @@
1
+ require 'initializer' unless defined? ::Rails::Initializer
2
+ require 'action_controller/dispatcher' unless defined? ::ActionController::Dispatcher
3
+
4
+ module HasManyPolymorphs
5
+
6
+ =begin rdoc
7
+ Searches for models that use <tt>has_many_polymorphs</tt> or <tt>acts_as_double_polymorphic_join</tt> and makes sure that they get loaded during app initialization. This ensures that helper methods are injected into the target classes.
8
+
9
+ Note that you can override DEFAULT_OPTIONS via Rails::Configuration#has_many_polymorphs_options. For example, if you need an application extension to be required before has_many_polymorphs loads your models, add an <tt>after_initialize</tt> block in <tt>config/environment.rb</tt> that appends to the <tt>'requirements'</tt> key:
10
+ Rails::Initializer.run do |config|
11
+ # your other configuration here
12
+
13
+ config.after_initialize do
14
+ config.has_many_polymorphs_options['requirements'] << 'lib/my_extension'
15
+ end
16
+ end
17
+
18
+ =end
19
+
20
+ MODELS_ROOT = "#{RAILS_ROOT}/app/models/"
21
+
22
+ DEFAULT_OPTIONS = {
23
+ :file_pattern => "#{MODELS_ROOT}**/*.rb",
24
+ :file_exclusions => ['svn', 'CVS', 'bzr'],
25
+ :methods => ['has_many_polymorphs', 'acts_as_double_polymorphic_join'],
26
+ :requirements => []}
27
+
28
+ mattr_accessor :options
29
+ @@options = HashWithIndifferentAccess.new(DEFAULT_OPTIONS)
30
+
31
+
32
+ # Dispatcher callback to load polymorphic relationships from the top down.
33
+ def self.autoload
34
+
35
+ _logger_debug "autoload hook invoked"
36
+
37
+ options[:requirements].each do |requirement|
38
+ _logger_warn "forcing requirement load of #{requirement}"
39
+ require requirement
40
+ end
41
+
42
+ Dir.glob(options[:file_pattern]).each do |filename|
43
+ next if filename =~ /#{options[:file_exclusions].join("|")}/
44
+ open(filename) do |file|
45
+ if file.grep(/#{options[:methods].join("|")}/).any?
46
+ begin
47
+ modelname = filename[0..-4]
48
+ modelname.slice!(MODELS_ROOT)
49
+ model = modelname.camelize
50
+ _logger_warn "preloading parent model #{model}"
51
+ model.constantize
52
+ rescue Object => e
53
+ _logger_warn "#{model} could not be preloaded: #{e.inspect}"
54
+ end
55
+ end
56
+ end
57
+ end
58
+ end
59
+
60
+ end
61
+
62
+ class Rails::Initializer #:nodoc:
63
+ # Make sure it gets loaded in the console, tests, and migrations
64
+ def after_initialize_with_autoload
65
+ after_initialize_without_autoload
66
+ HasManyPolymorphs.autoload
67
+ end
68
+ alias_method_chain :after_initialize, :autoload
69
+ end
70
+
71
+ ActionController::Dispatcher.to_prepare(:has_many_polymorphs_autoload) do
72
+ # Make sure it gets loaded in the app
73
+ HasManyPolymorphs.autoload
74
+ end
@@ -0,0 +1,60 @@
1
+
2
+ module ActiveRecord
3
+ class Base
4
+
5
+ class << self
6
+
7
+ # Interprets a polymorphic row from a unified SELECT, returning the appropriate ActiveRecord instance. Overrides ActiveRecord::Base.instantiate_without_callbacks.
8
+ def instantiate_with_polymorphic_checks(record)
9
+ if record['polymorphic_parent_class']
10
+ reflection = record['polymorphic_parent_class'].constantize.reflect_on_association(record['polymorphic_association_id'].to_sym)
11
+ # _logger_debug "Instantiating a polymorphic row for #{record['polymorphic_parent_class']}.reflect_on_association(:#{record['polymorphic_association_id']})"
12
+
13
+ # rewrite the record with the right column names
14
+ table_aliases = reflection.options[:table_aliases].dup
15
+ record = Hash[*table_aliases.keys.map {|key| [key, record[table_aliases[key]]] }.flatten]
16
+
17
+ # find the real child class
18
+ klass = record["#{self.table_name}.#{reflection.options[:polymorphic_type_key]}"].constantize
19
+ if sti_klass = record["#{klass.table_name}.#{klass.inheritance_column}"]
20
+ klass = klass.class_eval do compute_type(sti_klass) end # in case of namespaced STI models
21
+ end
22
+
23
+ # check that the join actually joined to something
24
+ unless (child_id = record["#{self.table_name}.#{reflection.options[:polymorphic_key]}"]) == record["#{klass.table_name}.#{klass.primary_key}"]
25
+ raise ActiveRecord::Associations::PolymorphicError,
26
+ "Referential integrity violation; child <#{klass.name}:#{child_id}> was not found for #{reflection.name.inspect}"
27
+ end
28
+
29
+ # eject the join keys
30
+ # XXX not very readable
31
+ record = Hash[*record._select do |column, value|
32
+ column[/^#{klass.table_name}/]
33
+ end.map do |column, value|
34
+ [column[/\.(.*)/, 1], value]
35
+ end.flatten]
36
+
37
+ # allocate and assign values
38
+ klass.allocate.tap do |obj|
39
+ obj.instance_variable_set("@attributes", record)
40
+ obj.instance_variable_set("@attributes_cache", Hash.new)
41
+
42
+ if obj.respond_to_without_attributes?(:after_find)
43
+ obj.send(:callback, :after_find)
44
+ end
45
+
46
+ if obj.respond_to_without_attributes?(:after_initialize)
47
+ obj.send(:callback, :after_initialize)
48
+ end
49
+
50
+ end
51
+ else
52
+ instantiate_without_polymorphic_checks(record)
53
+ end
54
+ end
55
+
56
+ alias_method_chain :instantiate, :polymorphic_checks
57
+ end
58
+
59
+ end
60
+ end
@@ -0,0 +1,600 @@
1
+
2
+ module ActiveRecord #:nodoc:
3
+ module Associations #:nodoc:
4
+
5
+ =begin rdoc
6
+
7
+ Class methods added to ActiveRecord::Base for setting up polymorphic associations.
8
+
9
+ == Notes
10
+
11
+ STI association targets must enumerated and named. For example, if Dog and Cat both inherit from Animal, you still need to say <tt>[:dogs, :cats]</tt>, and not <tt>[:animals]</tt>.
12
+
13
+ Namespaced models follow the Rails <tt>underscore</tt> convention. ZooAnimal::Lion becomes <tt>:'zoo_animal/lion'</tt>.
14
+
15
+ You do not need to set up any other associations other than for either the regular method or the double. The join associations and all individual and reverse associations are generated for you. However, a join model and table are required.
16
+
17
+ There is a tentative report that you can make the parent model be its own join model, but this is untested.
18
+
19
+ =end
20
+
21
+ module PolymorphicClassMethods
22
+
23
+ RESERVED_DOUBLES_KEYS = [:conditions, :order, :limit, :offset, :extend, :skip_duplicates,
24
+ :join_extend, :dependent, :rename_individual_collections,
25
+ :namespace] #:nodoc:
26
+
27
+ =begin rdoc
28
+
29
+ This method creates a doubled-sided polymorphic relationship. It must be called on the join model:
30
+
31
+ class Devouring < ActiveRecord::Base
32
+ belongs_to :eater, :polymorphic => true
33
+ belongs_to :eaten, :polymorphic => true
34
+
35
+ acts_as_double_polymorphic_join(
36
+ :eaters => [:dogs, :cats],
37
+ :eatens => [:cats, :birds]
38
+ )
39
+ end
40
+
41
+ The method works by defining one or more special <tt>has_many_polymorphs</tt> association on every model in the target lists, depending on which side of the association it is on. Double self-references will work.
42
+
43
+ The two association names and their value arrays are the only required parameters.
44
+
45
+ == Available options
46
+
47
+ These options are passed through to targets on both sides of the association. If you want to affect only one side, prepend the key with the name of that side. For example, <tt>:eaters_extend</tt>.
48
+
49
+ <tt>:dependent</tt>:: Accepts <tt>:destroy</tt>, <tt>:nullify</tt>, or <tt>:delete_all</tt>. Controls how the join record gets treated on any association delete (whether from the polymorph or from an individual collection); defaults to <tt>:destroy</tt>.
50
+ <tt>:skip_duplicates</tt>:: If <tt>true</tt>, will check to avoid pushing already associated records (but also triggering a database load). Defaults to <tt>true</tt>.
51
+ <tt>:rename_individual_collections</tt>:: If <tt>true</tt>, all individual collections are prepended with the polymorph name, and the children's parent collection is appended with <tt>"\_of_#{association_name}"</tt>.
52
+ <tt>:extend</tt>:: One or an array of mixed modules and procs, which are applied to the polymorphic association (usually to define custom methods).
53
+ <tt>:join_extend</tt>:: One or an array of mixed modules and procs, which are applied to the join association.
54
+ <tt>:conditions</tt>:: An array or string of conditions for the SQL <tt>WHERE</tt> clause.
55
+ <tt>:order</tt>:: A string for the SQL <tt>ORDER BY</tt> clause.
56
+ <tt>:limit</tt>:: An integer. Affects the polymorphic and individual associations.
57
+ <tt>:offset</tt>:: An integer. Only affects the polymorphic association.
58
+ <tt>:namespace</tt>:: A symbol. Prepended to all the models in the <tt>:from</tt> and <tt>:through</tt> keys. This is especially useful for Camping, which namespaces models by default.
59
+
60
+ =end
61
+
62
+ def acts_as_double_polymorphic_join options={}, &extension
63
+
64
+ collections, options = extract_double_collections(options)
65
+
66
+ # handle the block
67
+ options[:extend] = (if options[:extend]
68
+ Array(options[:extend]) + [extension]
69
+ else
70
+ extension
71
+ end) if extension
72
+
73
+ collection_option_keys = make_general_option_keys_specific!(options, collections)
74
+
75
+ join_name = self.name.tableize.to_sym
76
+ collections.each do |association_id, children|
77
+ parent_hash_key = (collections.keys - [association_id]).first # parents are the entries in the _other_ children array
78
+
79
+ begin
80
+ parent_foreign_key = self.reflect_on_association(parent_hash_key._singularize).primary_key_name
81
+ rescue NoMethodError
82
+ raise PolymorphicError, "Couldn't find 'belongs_to' association for :#{parent_hash_key._singularize} in #{self.name}." unless parent_foreign_key
83
+ end
84
+
85
+ parents = collections[parent_hash_key]
86
+ conflicts = (children & parents) # set intersection
87
+ parents.each do |plural_parent_name|
88
+
89
+ parent_class = plural_parent_name._as_class
90
+ singular_reverse_association_id = parent_hash_key._singularize
91
+
92
+ internal_options = {
93
+ :is_double => true,
94
+ :from => children,
95
+ :as => singular_reverse_association_id,
96
+ :through => join_name.to_sym,
97
+ :foreign_key => parent_foreign_key,
98
+ :foreign_type_key => parent_foreign_key.to_s.sub(/_id$/, '_type'),
99
+ :singular_reverse_association_id => singular_reverse_association_id,
100
+ :conflicts => conflicts
101
+ }
102
+
103
+ general_options = Hash[*options._select do |key, value|
104
+ collection_option_keys[association_id].include? key and !value.nil?
105
+ end.map do |key, value|
106
+ [key.to_s[association_id.to_s.length+1..-1].to_sym, value]
107
+ end._flatten_once] # rename side-specific options to general names
108
+
109
+ general_options.each do |key, value|
110
+ # avoid clobbering keys that appear in both option sets
111
+ if internal_options[key]
112
+ general_options[key] = Array(value) + Array(internal_options[key])
113
+ end
114
+ end
115
+
116
+ parent_class.send(:has_many_polymorphs, association_id, internal_options.merge(general_options))
117
+
118
+ if conflicts.include? plural_parent_name
119
+ # unify the alternate sides of the conflicting children
120
+ (conflicts).each do |method_name|
121
+ unless parent_class.instance_methods.include?(method_name)
122
+ parent_class.send(:define_method, method_name) do
123
+ (self.send("#{singular_reverse_association_id}_#{method_name}") +
124
+ self.send("#{association_id._singularize}_#{method_name}")).freeze
125
+ end
126
+ end
127
+ end
128
+
129
+ # unify the join model... join model is always renamed for doubles, unlike child associations
130
+ unless parent_class.instance_methods.include?(join_name)
131
+ parent_class.send(:define_method, join_name) do
132
+ (self.send("#{join_name}_as_#{singular_reverse_association_id}") +
133
+ self.send("#{join_name}_as_#{association_id._singularize}")).freeze
134
+ end
135
+ end
136
+ else
137
+ unless parent_class.instance_methods.include?(join_name)
138
+ parent_class.send(:alias_method, join_name, "#{join_name}_as_#{singular_reverse_association_id}")
139
+ end
140
+ end
141
+
142
+ end
143
+ end
144
+ end
145
+
146
+ private
147
+
148
+ def extract_double_collections(options)
149
+ collections = options._select do |key, value|
150
+ value.is_a? Array and key.to_s !~ /(#{RESERVED_DOUBLES_KEYS.map(&:to_s).join('|')})$/
151
+ end
152
+
153
+ raise PolymorphicError, "Couldn't understand options in acts_as_double_polymorphic_join. Valid parameters are your two class collections, and then #{RESERVED_DOUBLES_KEYS.inspect[1..-2]}, with optionally your collection names prepended and joined with an underscore." unless collections.size == 2
154
+
155
+ options = options._select do |key, value|
156
+ !collections[key]
157
+ end
158
+
159
+ [collections, options]
160
+ end
161
+
162
+ def make_general_option_keys_specific!(options, collections)
163
+ collection_option_keys = Hash[*collections.keys.map do |key|
164
+ [key, RESERVED_DOUBLES_KEYS.map{|option| "#{key}_#{option}".to_sym}]
165
+ end._flatten_once]
166
+
167
+ collections.keys.each do |collection|
168
+ options.each do |key, value|
169
+ next if collection_option_keys.values.flatten.include? key
170
+ # shift the general options to the individual sides
171
+ collection_key = "#{collection}_#{key}".to_sym
172
+ collection_value = options[collection_key]
173
+ case key
174
+ when :conditions
175
+ collection_value, value = sanitize_sql(collection_value), sanitize_sql(value)
176
+ options[collection_key] = (collection_value ? "(#{collection_value}) AND (#{value})" : value)
177
+ when :order
178
+ options[collection_key] = (collection_value ? "#{collection_value}, #{value}" : value)
179
+ when :extend, :join_extend
180
+ options[collection_key] = Array(collection_value) + Array(value)
181
+ else
182
+ options[collection_key] ||= value
183
+ end
184
+ end
185
+ end
186
+
187
+ collection_option_keys
188
+ end
189
+
190
+
191
+
192
+ public
193
+
194
+ =begin rdoc
195
+
196
+ This method createds a single-sided polymorphic relationship.
197
+
198
+ class Petfood < ActiveRecord::Base
199
+ has_many_polymorphs :eaters, :from => [:dogs, :cats, :birds]
200
+ end
201
+
202
+ The only required parameter, aside from the association name, is <tt>:from</tt>.
203
+
204
+ The method generates a number of associations aside from the polymorphic one. In this example Petfood also gets <tt>dogs</tt>, <tt>cats</tt>, and <tt>birds</tt>, and Dog, Cat, and Bird get <tt>petfoods</tt>. (The reverse association to the parents is always plural.)
205
+
206
+ == Available options
207
+
208
+ <tt>:from</tt>:: An array of symbols representing the target models. Required.
209
+ <tt>:as</tt>:: A symbol for the parent's interface in the join--what the parent 'acts as'.
210
+ <tt>:through</tt>:: A symbol representing the class of the join model. Follows Rails defaults if not supplied (the parent and the association names, alphabetized, concatenated with an underscore, and singularized).
211
+ <tt>:dependent</tt>:: Accepts <tt>:destroy</tt>, <tt>:nullify</tt>, <tt>:delete_all</tt>. Controls how the join record gets treated on any associate delete (whether from the polymorph or from an individual collection); defaults to <tt>:destroy</tt>.
212
+ <tt>:skip_duplicates</tt>:: If <tt>true</tt>, will check to avoid pushing already associated records (but also triggering a database load). Defaults to <tt>true</tt>.
213
+ <tt>:rename_individual_collections</tt>:: If <tt>true</tt>, all individual collections are prepended with the polymorph name, and the children's parent collection is appended with "_of_#{association_name}"</tt>. For example, <tt>zoos</tt> becomes <tt>zoos_of_animals</tt>. This is to help avoid method name collisions in crowded classes.
214
+ <tt>:extend</tt>:: One or an array of mixed modules and procs, which are applied to the polymorphic association (usually to define custom methods).
215
+ <tt>:join_extend</tt>:: One or an array of mixed modules and procs, which are applied to the join association.
216
+ <tt>:parent_extend</tt>:: One or an array of mixed modules and procs, which are applied to the target models' association to the parents.
217
+ <tt>:conditions</tt>:: An array or string of conditions for the SQL <tt>WHERE</tt> clause.
218
+ <tt>:parent_conditions</tt>:: An array or string of conditions which are applied to the target models' association to the parents.
219
+ <tt>:order</tt>:: A string for the SQL <tt>ORDER BY</tt> clause.
220
+ <tt>:parent_order</tt>:: A string for the SQL <tt>ORDER BY</tt> which is applied to the target models' association to the parents.
221
+ <tt>:group</tt>:: An array or string of conditions for the SQL <tt>GROUP BY</tt> clause. Affects the polymorphic and individual associations.
222
+ <tt>:limit</tt>:: An integer. Affects the polymorphic and individual associations.
223
+ <tt>:offset</tt>:: An integer. Only affects the polymorphic association.
224
+ <tt>:namespace</tt>:: A symbol. Prepended to all the models in the <tt>:from</tt> and <tt>:through</tt> keys. This is especially useful for Camping, which namespaces models by default.
225
+ <tt>:uniq</tt>:: If <tt>true</tt>, the records returned are passed through a pure-Ruby <tt>uniq</tt> before they are returned. Rarely needed.
226
+ <tt>:foreign_key</tt>:: The column name for the parent's id in the join.
227
+ <tt>:foreign_type_key</tt>:: The column name for the parent's class name in the join, if the parent itself is polymorphic. Rarely needed--if you're thinking about using this, you almost certainly want to use <tt>acts_as_double_polymorphic_join()</tt> instead.
228
+ <tt>:polymorphic_key</tt>:: The column name for the child's id in the join.
229
+ <tt>:polymorphic_type_key</tt>:: The column name for the child's class name in the join.
230
+
231
+ If you pass a block, it gets converted to a Proc and added to <tt>:extend</tt>.
232
+
233
+ == On condition nullification
234
+
235
+ When you request an individual association, non-applicable but fully-qualified fields in the polymorphic association's <tt>:conditions</tt>, <tt>:order</tt>, and <tt>:group</tt> options get changed to <tt>NULL</tt>. For example, if you set <tt>:conditions => "dogs.name != 'Spot'"</tt>, when you request <tt>.cats</tt>, the conditions string is changed to <tt>NULL != 'Spot'</tt>.
236
+
237
+ Be aware, however, that <tt>NULL != 'Spot'</tt> returns <tt>false</tt> due to SQL's 3-value logic. Instead, you need to use the <tt>:conditions</tt> string <tt>"dogs.name IS NULL OR dogs.name != 'Spot'"</tt> to get the behavior you probably expect for negative matches.
238
+
239
+ =end
240
+
241
+ def has_many_polymorphs (association_id, options = {}, &extension)
242
+ _logger_debug "associating #{self}.#{association_id}"
243
+ reflection = create_has_many_polymorphs_reflection(association_id, options, &extension)
244
+ # puts "Created reflection #{reflection.inspect}"
245
+ # configure_dependency_for_has_many(reflection)
246
+ collection_reader_method(reflection, PolymorphicAssociation)
247
+ end
248
+
249
+ # Composed method that assigns option defaults, builds the reflection object, and sets up all the related associations on the parent, join, and targets.
250
+ def create_has_many_polymorphs_reflection(association_id, options, &extension) #:nodoc:
251
+ options.assert_valid_keys(
252
+ :from,
253
+ :as,
254
+ :through,
255
+ :foreign_key,
256
+ :foreign_type_key,
257
+ :polymorphic_key, # same as :association_foreign_key
258
+ :polymorphic_type_key,
259
+ :dependent, # default :destroy, only affects the join table
260
+ :skip_duplicates, # default true, only affects the polymorphic collection
261
+ :ignore_duplicates, # deprecated
262
+ :is_double,
263
+ :rename_individual_collections,
264
+ :reverse_association_id, # not used
265
+ :singular_reverse_association_id,
266
+ :conflicts,
267
+ :extend,
268
+ :join_class_name,
269
+ :join_extend,
270
+ :parent_extend,
271
+ :table_aliases,
272
+ :select, # applies to the polymorphic relationship
273
+ :conditions, # applies to the polymorphic relationship, the children, and the join
274
+ # :include,
275
+ :parent_conditions,
276
+ :parent_order,
277
+ :order, # applies to the polymorphic relationship, the children, and the join
278
+ :group, # only applies to the polymorphic relationship and the children
279
+ :limit, # only applies to the polymorphic relationship and the children
280
+ :offset, # only applies to the polymorphic relationship
281
+ :parent_order,
282
+ :parent_group,
283
+ :parent_limit,
284
+ :parent_offset,
285
+ # :source,
286
+ :namespace,
287
+ :uniq, # XXX untested, only applies to the polymorphic relationship
288
+ # :finder_sql,
289
+ # :counter_sql,
290
+ # :before_add,
291
+ # :after_add,
292
+ # :before_remove,
293
+ # :after_remove
294
+ :dummy)
295
+
296
+ # validate against the most frequent configuration mistakes
297
+ verify_pluralization_of(association_id)
298
+ raise PolymorphicError, ":from option must be an array" unless options[:from].is_a? Array
299
+ options[:from].each{|plural| verify_pluralization_of(plural)}
300
+
301
+ options[:as] ||= self.name.demodulize.underscore.to_sym
302
+ options[:conflicts] = Array(options[:conflicts])
303
+ options[:foreign_key] ||= "#{options[:as]}_id"
304
+
305
+ options[:association_foreign_key] =
306
+ options[:polymorphic_key] ||= "#{association_id._singularize}_id"
307
+ options[:polymorphic_type_key] ||= "#{association_id._singularize}_type"
308
+
309
+ if options.has_key? :ignore_duplicates
310
+ _logger_warn "DEPRECATION WARNING: please use :skip_duplicates instead of :ignore_duplicates"
311
+ options[:skip_duplicates] = options[:ignore_duplicates]
312
+ end
313
+ options[:skip_duplicates] = true unless options.has_key? :skip_duplicates
314
+ options[:dependent] = :destroy unless options.has_key? :dependent
315
+ options[:conditions] = sanitize_sql(options[:conditions])
316
+
317
+ # options[:finder_sql] ||= "(options[:polymorphic_key]
318
+
319
+ options[:through] ||= build_join_table_symbol(association_id, (options[:as]._pluralize or self.table_name))
320
+
321
+ # set up namespaces if we have a namespace key
322
+ # XXX needs test coverage
323
+ if options[:namespace]
324
+ namespace = options[:namespace].to_s.chomp("/") + "/"
325
+ options[:from].map! do |child|
326
+ "#{namespace}#{child}".to_sym
327
+ end
328
+ options[:through] = "#{namespace}#{options[:through]}".to_sym
329
+ end
330
+
331
+ options[:join_class_name] ||= options[:through]._classify
332
+ options[:table_aliases] ||= build_table_aliases([options[:through]] + options[:from])
333
+ options[:select] ||= build_select(association_id, options[:table_aliases])
334
+
335
+ options[:through] = "#{options[:through]}_as_#{options[:singular_reverse_association_id]}" if options[:singular_reverse_association_id]
336
+ options[:through] = demodulate(options[:through]).to_sym
337
+
338
+ options[:extend] = spiked_create_extension_module(association_id, Array(options[:extend]) + Array(extension))
339
+ options[:join_extend] = spiked_create_extension_module(association_id, Array(options[:join_extend]), "Join")
340
+ options[:parent_extend] = spiked_create_extension_module(association_id, Array(options[:parent_extend]), "Parent")
341
+
342
+ # create the reflection object
343
+ create_reflection(:has_many_polymorphs, association_id, options, self).tap do |reflection|
344
+ # set up the other related associations
345
+ create_join_association(association_id, reflection)
346
+ create_has_many_through_associations_for_parent_to_children(association_id, reflection)
347
+ create_has_many_through_associations_for_children_to_parent(association_id, reflection)
348
+ end
349
+ end
350
+
351
+ private
352
+
353
+
354
+ # table mapping for use at the instantiation point
355
+
356
+ def build_table_aliases(from)
357
+ # for the targets
358
+ {}.tap do |aliases|
359
+ from.map(&:to_s).sort.map(&:to_sym).each_with_index do |plural, t_index|
360
+ begin
361
+ table = plural._as_class.table_name
362
+ rescue NameError => e
363
+ raise PolymorphicError, "Could not find a valid class for #{plural.inspect} (tried #{plural.to_s._classify}). If it's namespaced, be sure to specify it as :\"module/#{plural}\" instead."
364
+ end
365
+ begin
366
+ plural._as_class.columns.map(&:name).each_with_index do |field, f_index|
367
+ aliases["#{table}.#{field}"] = "t#{t_index}_r#{f_index}"
368
+ end
369
+ rescue ActiveRecord::StatementInvalid => e
370
+ _logger_warn "Looks like your table doesn't exist for #{plural.to_s._classify}.\nError #{e}\nSkipping..."
371
+ end
372
+ end
373
+ end
374
+ end
375
+
376
+ def build_select(association_id, aliases)
377
+ # <tt>instantiate</tt> has to know which reflection the results are coming from
378
+ (["\'#{self.name}\' AS polymorphic_parent_class",
379
+ "\'#{association_id}\' AS polymorphic_association_id"] +
380
+ aliases.map do |table, _alias|
381
+ "#{table} AS #{_alias}"
382
+ end.sort).join(", ")
383
+ end
384
+
385
+ # method sub-builders
386
+
387
+ def create_join_association(association_id, reflection)
388
+
389
+ options = {
390
+ :foreign_key => reflection.options[:foreign_key],
391
+ :dependent => reflection.options[:dependent],
392
+ :class_name => reflection.klass.name,
393
+ :extend => reflection.options[:join_extend]
394
+ # :limit => reflection.options[:limit],
395
+ # :offset => reflection.options[:offset],
396
+ # :order => devolve(association_id, reflection, reflection.options[:order], reflection.klass, true),
397
+ # :conditions => devolve(association_id, reflection, reflection.options[:conditions], reflection.klass, true)
398
+ }
399
+
400
+ if reflection.options[:foreign_type_key]
401
+ type_check = "#{reflection.options[:join_class_name].constantize.quoted_table_name}.#{reflection.options[:foreign_type_key]} = #{quote_value(self.base_class.name)}"
402
+ conjunction = options[:conditions] ? " AND " : nil
403
+ options[:conditions] = "#{options[:conditions]}#{conjunction}#{type_check}"
404
+ options[:as] = reflection.options[:as]
405
+ end
406
+
407
+ has_many(reflection.options[:through], options)
408
+
409
+ inject_before_save_into_join_table(association_id, reflection)
410
+ end
411
+
412
+ def inject_before_save_into_join_table(association_id, reflection)
413
+ sti_hook = "sti_class_rewrite"
414
+ rewrite_procedure = %[self.send(:#{reflection.options[:polymorphic_type_key]}=, self.#{reflection.options[:polymorphic_type_key]}.constantize.base_class.name)]
415
+
416
+ # XXX should be abstracted?
417
+ reflection.klass.class_eval %[
418
+ unless instance_methods.include? "before_save_with_#{sti_hook}"
419
+ if instance_methods.include? "before_save"
420
+ alias_method :before_save_without_#{sti_hook}, :before_save
421
+ def before_save_with_#{sti_hook}
422
+ before_save_without_#{sti_hook}
423
+ #{rewrite_procedure}
424
+ end
425
+ else
426
+ def before_save_with_#{sti_hook}
427
+ #{rewrite_procedure}
428
+ end
429
+ end
430
+ alias_method :before_save, :before_save_with_#{sti_hook}
431
+ end
432
+ ]
433
+ end
434
+
435
+ def create_has_many_through_associations_for_children_to_parent(association_id, reflection)
436
+
437
+ child_pluralization_map(association_id, reflection).each do |plural, singular|
438
+ if singular == reflection.options[:as]
439
+ raise PolymorphicError, if reflection.options[:is_double]
440
+ "You can't give either of the sides in a double-polymorphic join the same name as any of the individual target classes."
441
+ else
442
+ "You can't have a self-referential polymorphic has_many :through without renaming the non-polymorphic foreign key in the join model."
443
+ end
444
+ end
445
+
446
+ parent = self
447
+ plural._as_class.instance_eval do
448
+ # this shouldn't be called at all during doubles; there is no way to traverse to a double polymorphic parent (XXX is that right?)
449
+ unless reflection.options[:is_double] or reflection.options[:conflicts].include? self.name.tableize.to_sym
450
+
451
+ # the join table
452
+ through = "#{reflection.options[:through]}#{'_as_child' if parent == self}".to_sym
453
+ has_many(through,
454
+ :as => association_id._singularize,
455
+ # :source => association_id._singularize,
456
+ # :source_type => reflection.options[:polymorphic_type_key],
457
+ :class_name => reflection.klass.name,
458
+ :dependent => reflection.options[:dependent],
459
+ :extend => reflection.options[:join_extend],
460
+ # :limit => reflection.options[:limit],
461
+ # :offset => reflection.options[:offset],
462
+ :order => devolve(association_id, reflection, reflection.options[:parent_order], reflection.klass),
463
+ :conditions => devolve(association_id, reflection, reflection.options[:parent_conditions], reflection.klass)
464
+ )
465
+
466
+ # the association to the target's parents
467
+ association = "#{reflection.options[:as]._pluralize}#{"_of_#{association_id}" if reflection.options[:rename_individual_collections]}".to_sym
468
+ has_many(association,
469
+ :through => through,
470
+ :class_name => parent.name,
471
+ :source => reflection.options[:as],
472
+ :foreign_key => reflection.options[:foreign_key],
473
+ :extend => reflection.options[:parent_extend],
474
+ :conditions => reflection.options[:parent_conditions],
475
+ :order => reflection.options[:parent_order],
476
+ :offset => reflection.options[:parent_offset],
477
+ :limit => reflection.options[:parent_limit],
478
+ :group => reflection.options[:parent_group])
479
+
480
+ # debugger if association == :parents
481
+ #
482
+ # nil
483
+
484
+ end
485
+ end
486
+ end
487
+ end
488
+
489
+ def create_has_many_through_associations_for_parent_to_children(association_id, reflection)
490
+ child_pluralization_map(association_id, reflection).each do |plural, singular|
491
+ #puts ":source => #{child}"
492
+ current_association = demodulate(child_association_map(association_id, reflection)[plural])
493
+ source = demodulate(singular)
494
+
495
+ if reflection.options[:conflicts].include? plural
496
+ # XXX check this
497
+ current_association = "#{association_id._singularize}_#{current_association}" if reflection.options[:conflicts].include? self.name.tableize.to_sym
498
+ source = "#{source}_as_#{association_id._singularize}".to_sym
499
+ end
500
+
501
+ # make push/delete accessible from the individual collections but still operate via the general collection
502
+ extension_module = self.class_eval %[
503
+ module #{self.name + current_association._classify + "PolymorphicChildAssociationExtension"}
504
+ def push *args; proxy_owner.send(:#{association_id}).send(:push, *args); self; end
505
+ alias :<< :push
506
+ def delete *args; proxy_owner.send(:#{association_id}).send(:delete, *args); end
507
+ def clear; proxy_owner.send(:#{association_id}).send(:clear, #{singular._classify}); end
508
+ self
509
+ end]
510
+
511
+ has_many(current_association.to_sym,
512
+ :through => reflection.options[:through],
513
+ :source => association_id._singularize,
514
+ :source_type => plural._as_class.base_class.name,
515
+ :class_name => plural._as_class.name, # make STI not conflate subtypes
516
+ :extend => (Array(extension_module) + reflection.options[:extend]),
517
+ :limit => reflection.options[:limit],
518
+ # :offset => reflection.options[:offset],
519
+ :order => devolve(association_id, reflection, reflection.options[:order], plural._as_class),
520
+ :conditions => devolve(association_id, reflection, reflection.options[:conditions], plural._as_class),
521
+ :group => devolve(association_id, reflection, reflection.options[:group], plural._as_class)
522
+ )
523
+
524
+ end
525
+ end
526
+
527
+ # some support methods
528
+
529
+ def child_pluralization_map(association_id, reflection)
530
+ Hash[*reflection.options[:from].map do |plural|
531
+ [plural, plural._singularize]
532
+ end.flatten]
533
+ end
534
+
535
+ def child_association_map(association_id, reflection)
536
+ Hash[*reflection.options[:from].map do |plural|
537
+ [plural, "#{association_id._singularize.to_s + "_" if reflection.options[:rename_individual_collections]}#{plural}".to_sym]
538
+ end.flatten]
539
+ end
540
+
541
+ def demodulate(s)
542
+ s.to_s.gsub('/', '_').to_sym
543
+ end
544
+
545
+ def build_join_table_symbol(association_id, name)
546
+ [name.to_s, association_id.to_s].sort.join("_").to_sym
547
+ end
548
+
549
+ def all_classes_for(association_id, reflection)
550
+ klasses = [self, reflection.klass, *child_pluralization_map(association_id, reflection).keys.map(&:_as_class)]
551
+ klasses += klasses.map(&:base_class)
552
+ klasses.uniq
553
+ end
554
+
555
+ def devolve(association_id, reflection, string, klass, remove_inappropriate_clauses = false)
556
+ # XXX remove_inappropriate_clauses is not implemented; we'll wait until someone actually needs it
557
+ return unless string
558
+ string = string.dup
559
+ # _logger_debug "devolving #{string} for #{klass}"
560
+ inappropriate_classes = (all_classes_for(association_id, reflection) - # the join class must always be preserved
561
+ [klass, klass.base_class, reflection.klass, reflection.klass.base_class])
562
+ inappropriate_classes.map do |klass|
563
+ klass.columns.map do |column|
564
+ [klass.table_name, column.name]
565
+ end.map do |table, column|
566
+ ["#{table}.#{column}", "`#{table}`.#{column}", "#{table}.`#{column}`", "`#{table}`.`#{column}`"]
567
+ end
568
+ end.flatten.sort_by(&:size).reverse.each do |quoted_reference|
569
+ # _logger_debug "devolved #{quoted_reference} to NULL"
570
+ # XXX clause removal would go here
571
+ string.gsub!(quoted_reference, "NULL")
572
+ end
573
+ # _logger_debug "altered to #{string}"
574
+ string
575
+ end
576
+
577
+ def verify_pluralization_of(sym)
578
+ sym = sym.to_s
579
+ singular = sym.singularize
580
+ plural = singular.pluralize
581
+ raise PolymorphicError, "Pluralization rules not set up correctly. You passed :#{sym}, which singularizes to :#{singular}, but that pluralizes to :#{plural}, which is different. Maybe you meant :#{plural} to begin with?" unless sym == plural
582
+ end
583
+
584
+ def spiked_create_extension_module(association_id, extensions, identifier = nil)
585
+ module_extensions = extensions.select{|e| e.is_a? Module}
586
+ proc_extensions = extensions.select{|e| e.is_a? Proc }
587
+
588
+ # support namespaced anonymous blocks as well as multiple procs
589
+ proc_extensions.each_with_index do |proc_extension, index|
590
+ module_name = "#{self.to_s}#{association_id._classify}Polymorphic#{identifier}AssociationExtension#{index}"
591
+ the_module = self.class_eval "module #{module_name}; self; end" # XXX hrm
592
+ the_module.class_eval &proc_extension
593
+ module_extensions << the_module
594
+ end
595
+ module_extensions
596
+ end
597
+
598
+ end
599
+ end
600
+ end