Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

root/tags/rel_2-0-2/activerecord/lib/active_record/reflection.rb

Revision 8207, 8.4 kB (checked in by david, 1 year ago)

Docfix (closes #10252)

Line 
1 module ActiveRecord
2   module Reflection # :nodoc:
3     def self.included(base)
4       base.extend(ClassMethods)
5     end
6
7     # Reflection allows you to interrogate Active Record classes and objects about their associations and aggregations.
8     # This information can, for example, be used in a form builder that took an Active Record object and created input
9     # fields for all of the attributes depending on their type and displayed the associations to other objects.
10     #
11     # You can find the interface for the AggregateReflection and AssociationReflection classes in the abstract MacroReflection class.
12     module ClassMethods
13       def create_reflection(macro, name, options, active_record)
14         case macro
15           when :has_many, :belongs_to, :has_one, :has_and_belongs_to_many
16             reflection = AssociationReflection.new(macro, name, options, active_record)
17           when :composed_of
18             reflection = AggregateReflection.new(macro, name, options, active_record)
19         end
20         write_inheritable_hash :reflections, name => reflection
21         reflection
22       end
23      
24       # Returns a hash containing all AssociationReflection objects for the current class
25       # Example:
26       #
27       #   Invoice.reflections
28       #   Account.reflections
29       #
30       def reflections
31         read_inheritable_attribute(:reflections) || write_inheritable_attribute(:reflections, {})
32       end
33        
34       # Returns an array of AggregateReflection objects for all the aggregations in the class.
35       def reflect_on_all_aggregations
36         reflections.values.select { |reflection| reflection.is_a?(AggregateReflection) }
37       end
38
39       # Returns the AggregateReflection object for the named +aggregation+ (use the symbol). Example:
40       #
41       #   Account.reflect_on_aggregation(:balance) # returns the balance AggregateReflection
42       #
43       def reflect_on_aggregation(aggregation)
44         reflections[aggregation].is_a?(AggregateReflection) ? reflections[aggregation] : nil
45       end
46
47       # Returns an array of AssociationReflection objects for all the associations in the class. If you only want to reflect on a
48       # certain association type, pass in the symbol (:has_many, :has_one, :belongs_to) for that as the first parameter.
49       # Example:
50       #
51       #   Account.reflect_on_all_associations             # returns an array of all associations
52       #   Account.reflect_on_all_associations(:has_many)  # returns an array of all has_many associations
53       #
54       def reflect_on_all_associations(macro = nil)
55         association_reflections = reflections.values.select { |reflection| reflection.is_a?(AssociationReflection) }
56         macro ? association_reflections.select { |reflection| reflection.macro == macro } : association_reflections
57       end
58
59       # Returns the AssociationReflection object for the named +association+ (use the symbol). Example:
60       #
61       #   Account.reflect_on_association(:owner) # returns the owner AssociationReflection
62       #   Invoice.reflect_on_association(:line_items).macro  # returns :has_many
63       #
64       def reflect_on_association(association)
65         reflections[association].is_a?(AssociationReflection) ? reflections[association] : nil
66       end
67     end
68
69
70     # Abstract base class for AggregateReflection and AssociationReflection that describes the interface available for both of
71     # those classes. Objects of AggregateReflection and AssociationReflection are returned by the Reflection::ClassMethods.
72     class MacroReflection
73       attr_reader :active_record
74
75       def initialize(macro, name, options, active_record)
76         @macro, @name, @options, @active_record = macro, name, options, active_record
77       end
78
79       # Returns the name of the macro, so it would return :balance for "composed_of :balance, :class_name => 'Money'" or
80       # :clients for "has_many :clients".
81       def name
82         @name
83       end
84
85       # Returns the type of the macro, so it would return :composed_of for
86       # "composed_of :balance, :class_name => 'Money'" or :has_many for "has_many :clients".
87       def macro
88         @macro
89       end
90
91       # Returns the hash of options used for the macro, so it would return { :class_name => "Money" } for
92       # "composed_of :balance, :class_name => 'Money'" or {} for "has_many :clients".
93       def options
94         @options
95       end
96
97       # Returns the class for the macro, so "composed_of :balance, :class_name => 'Money'" returns the Money class and
98       # "has_many :clients" returns the Client class.
99       def klass
100         @klass ||= class_name.constantize
101       end
102
103       def class_name
104         @class_name ||= options[:class_name] || derive_class_name
105       end
106
107       def ==(other_aggregation)
108         name == other_aggregation.name && other_aggregation.options && active_record == other_aggregation.active_record
109       end
110
111       private
112         def derive_class_name
113           name.to_s.camelize
114         end
115     end
116
117
118     # Holds all the meta-data about an aggregation as it was specified in the Active Record class.
119     class AggregateReflection < MacroReflection #:nodoc:
120     end
121
122     # Holds all the meta-data about an association as it was specified in the Active Record class.
123     class AssociationReflection < MacroReflection #:nodoc:
124       def klass
125         @klass ||= active_record.send(:compute_type, class_name)
126       end
127
128       def table_name
129         @table_name ||= klass.table_name
130       end
131
132       def primary_key_name
133         @primary_key_name ||= options[:foreign_key] || derive_primary_key_name
134       end
135
136       def association_foreign_key
137         @association_foreign_key ||= @options[:association_foreign_key] || class_name.foreign_key
138       end
139
140       def counter_cache_column
141         if options[:counter_cache] == true
142           "#{active_record.name.underscore.pluralize}_count"
143         elsif options[:counter_cache]
144           options[:counter_cache]
145         end
146       end
147
148       def through_reflection
149         @through_reflection ||= options[:through] ? active_record.reflect_on_association(options[:through]) : false
150       end
151
152       # Gets an array of possible :through source reflection names
153       #
154       #   [singularized, pluralized]
155       #
156       def source_reflection_names
157         @source_reflection_names ||= (options[:source] ? [options[:source]] : [name.to_s.singularize, name]).collect { |n| n.to_sym }
158       end
159
160       # Gets the source of the through reflection.  It checks both a singularized and pluralized form for :belongs_to or :has_many.
161       # (The :tags association on Tagging below)
162       #
163       #   class Post
164       #     has_many :tags, :through => :taggings
165       #   end
166       #
167       def source_reflection
168         return nil unless through_reflection
169         @source_reflection ||= source_reflection_names.collect { |name| through_reflection.klass.reflect_on_association(name) }.compact.first
170       end
171
172       def check_validity!
173         if options[:through]
174           if through_reflection.nil?
175             raise HasManyThroughAssociationNotFoundError.new(active_record.name, self)
176           end
177          
178           if source_reflection.nil?
179             raise HasManyThroughSourceAssociationNotFoundError.new(self)
180           end
181
182           if options[:source_type] && source_reflection.options[:polymorphic].nil?
183             raise HasManyThroughAssociationPointlessSourceTypeError.new(active_record.name, self, source_reflection)
184           end
185          
186           if source_reflection.options[:polymorphic] && options[:source_type].nil?
187             raise HasManyThroughAssociationPolymorphicError.new(active_record.name, self, source_reflection)
188           end
189          
190           unless [:belongs_to, :has_many].include?(source_reflection.macro) && source_reflection.options[:through].nil?
191             raise HasManyThroughSourceAssociationMacroError.new(self)
192           end
193         end
194       end
195
196       private
197         def derive_class_name
198           # get the class_name of the belongs_to association of the through reflection
199           if through_reflection
200             options[:source_type] || source_reflection.class_name
201           else
202             class_name = name.to_s.camelize
203             class_name = class_name.singularize if [ :has_many, :has_and_belongs_to_many ].include?(macro)
204             class_name
205           end
206         end
207
208         def derive_primary_key_name
209           if macro == :belongs_to
210             "#{name}_id"
211           elsif options[:as]
212             "#{options[:as]}_id"
213           else
214             active_record.name.foreign_key
215           end
216         end
217     end
218   end
219 end
Note: See TracBrowser for help on using the browser.