2 module Reflection
# :nodoc:
3 def self.included(base
)
4 base
.extend(ClassMethods
)
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.
11 # You can find the interface for the AggregateReflection and AssociationReflection classes in the abstract MacroReflection class.
13 def create_reflection(macro
, name
, options
, active_record
)
15 when :has_many, :belongs_to, :has_one, :has_and_belongs_to_many
16 klass
= options
[:through] ? ThroughReflection
: AssociationReflection
17 reflection
= klass
.new(macro
, name
, options
, active_record
)
19 reflection
= AggregateReflection
.new(macro
, name
, options
, active_record
)
21 write_inheritable_hash
:reflections, name
=> reflection
25 # Returns a hash containing all AssociationReflection objects for the current class
32 read_inheritable_attribute(:reflections) || write_inheritable_attribute(:reflections, {})
35 # Returns an array of AggregateReflection objects for all the aggregations in the class.
36 def reflect_on_all_aggregations
37 reflections
.values
.select
{ |reflection
| reflection
.is_a
?(AggregateReflection
) }
40 # Returns the AggregateReflection object for the named +aggregation+ (use the symbol). Example:
42 # Account.reflect_on_aggregation(:balance) # returns the balance AggregateReflection
44 def reflect_on_aggregation(aggregation
)
45 reflections
[aggregation
].is_a
?(AggregateReflection
) ? reflections
[aggregation
] : nil
48 # Returns an array of AssociationReflection objects for all the associations in the class. If you only want to reflect on a
49 # certain association type, pass in the symbol (<tt>:has_many</tt>, <tt>:has_one</tt>, <tt>:belongs_to</tt>) for that as the first parameter.
52 # Account.reflect_on_all_associations # returns an array of all associations
53 # Account.reflect_on_all_associations(:has_many) # returns an array of all has_many associations
55 def reflect_on_all_associations(macro
= nil)
56 association_reflections
= reflections
.values
.select
{ |reflection
| reflection
.is_a
?(AssociationReflection
) }
57 macro
? association_reflections
.select
{ |reflection
| reflection
.macro
== macro
} : association_reflections
60 # Returns the AssociationReflection object for the named +association+ (use the symbol). Example:
62 # Account.reflect_on_association(:owner) # returns the owner AssociationReflection
63 # Invoice.reflect_on_association(:line_items).macro # returns :has_many
65 def reflect_on_association(association
)
66 reflections
[association
].is_a
?(AssociationReflection
) ? reflections
[association
] : nil
71 # Abstract base class for AggregateReflection and AssociationReflection that describes the interface available for both of
72 # those classes. Objects of AggregateReflection and AssociationReflection are returned by the Reflection::ClassMethods.
74 attr_reader
:active_record
76 def initialize(macro
, name
, options
, active_record
)
77 @macro, @name, @options, @active_record = macro
, name
, options
, active_record
80 # Returns the name of the macro. For example, <tt>composed_of :balance, :class_name => 'Money'</tt> will return
81 # <tt>:balance</tt> or for <tt>has_many :clients</tt> it will return <tt>:clients</tt>.
86 # Returns the macro type. For example, <tt>composed_of :balance, :class_name => 'Money'</tt> will return <tt>:composed_of</tt>
87 # or for <tt>has_many :clients</tt> will return <tt>:has_many</tt>.
92 # Returns the hash of options used for the macro. For example, it would return <tt>{ :class_name => "Money" }</tt> for
93 # <tt>composed_of :balance, :class_name => 'Money'</tt> or +{}+ for <tt>has_many :clients</tt>.
98 # Returns the class for the macro. For example, <tt>composed_of :balance, :class_name => 'Money'</tt> returns the Money
99 # class and <tt>has_many :clients</tt> returns the Client class.
101 @klass ||= class_name
.constantize
104 # Returns the class name for the macro. For example, <tt>composed_of :balance, :class_name => 'Money'</tt> returns <tt>'Money'</tt>
105 # and <tt>has_many :clients</tt> returns <tt>'Client'</tt>.
107 @class_name ||= options
[:class_name] || derive_class_name
110 # Returns +true+ if +self+ and +other_aggregation+ have the same +name+ attribute, +active_record+ attribute,
111 # and +other_aggregation+ has an options hash assigned to it.
112 def ==(other_aggregation
)
113 other_aggregation
.kind_of
?(self.class) && name
== other_aggregation
.name
&& other_aggregation
.options
&& active_record
== other_aggregation
.active_record
116 def sanitized_conditions
#:nodoc:
117 @sanitized_conditions ||= klass
.send(:sanitize_sql, options
[:conditions]) if options
[:conditions]
120 # Returns +true+ if +self+ is a +belongs_to+ reflection.
126 def derive_class_name
132 # Holds all the meta-data about an aggregation as it was specified in the Active Record class.
133 class AggregateReflection
< MacroReflection
#:nodoc:
136 # Holds all the meta-data about an association as it was specified in the Active Record class.
137 class AssociationReflection
< MacroReflection
#:nodoc:
138 # Returns the target association's class:
140 # class Author < ActiveRecord::Base
144 # Author.reflect_on_association(:books).klass
147 # <b>Note:</b> do not call +klass.new+ or +klass.create+ to instantiate
148 # a new association object. Use +build_association+ or +create_association+
149 # instead. This allows plugins to hook into association object creation.
151 @klass ||= active_record
.send(:compute_type, class_name
)
154 # Returns a new, unsaved instance of the associated class. +options+ will
155 # be passed to the class's constructor.
156 def build_association(*options
)
160 # Creates a new instance of the associated class, and immediates saves it
161 # with ActiveRecord::Base#save. +options+ will be passed to the class's
162 # creation method. Returns the newly created object.
163 def create_association(*options
)
164 klass
.create(*options
)
167 # Creates a new instance of the associated class, and immediates saves it
168 # with ActiveRecord::Base#save!. +options+ will be passed to the class's
169 # creation method. If the created record doesn't pass validations, then an
170 # exception will be raised.
172 # Returns the newly created object.
173 def create_association
!(*options
)
174 klass
.create
!(*options
)
178 @table_name ||= klass
.table_name
181 def quoted_table_name
182 @quoted_table_name ||= klass
.quoted_table_name
186 @primary_key_name ||= options
[:foreign_key] || derive_primary_key_name
189 def association_foreign_key
190 @association_foreign_key ||= @options[:association_foreign_key] || class_name
.foreign_key
193 def counter_cache_column
194 if options
[:counter_cache] == true
195 "#{active_record.name.underscore.pluralize}_count"
196 elsif options
[:counter_cache]
197 options
[:counter_cache]
204 def through_reflection
208 def through_reflection_primary_key_name
211 def source_reflection
216 def derive_class_name
217 class_name
= name
.to_s
.camelize
218 class_name
= class_name
.singularize
if [ :has_many, :has_and_belongs_to_many ].include?(macro
)
222 def derive_primary_key_name
228 active_record
.name
.foreign_key
233 # Holds all the meta-data about a :through association as it was specified in the Active Record class.
234 class ThroughReflection
< AssociationReflection
#:nodoc:
235 # Gets the source of the through reflection. It checks both a singularized and pluralized form for <tt>:belongs_to</tt> or <tt>:has_many</tt>.
236 # (The <tt>:tags</tt> association on Tagging below.)
238 # class Post < ActiveRecord::Base
240 # has_many :tags, :through => :taggings
243 def source_reflection
244 @source_reflection ||= source_reflection_names
.collect
{ |name
| through_reflection
.klass
.reflect_on_association(name
) }.compact
.first
247 # Returns the AssociationReflection object specified in the <tt>:through</tt> option
248 # of a HasManyThrough or HasOneThrough association. Example:
250 # class Post < ActiveRecord::Base
252 # has_many :tags, :through => :taggings
255 # tags_reflection = Post.reflect_on_association(:tags)
256 # taggings_reflection = tags_reflection.through_reflection
258 def through_reflection
259 @through_reflection ||= active_record
.reflect_on_association(options
[:through])
262 # Gets an array of possible <tt>:through</tt> source reflection names:
264 # [:singularized, :pluralized]
266 def source_reflection_names
267 @source_reflection_names ||= (options
[:source] ? [options
[:source]] : [name
.to_s
.singularize
, name
]).collect
{ |n
| n
.to_sym
}
271 if through_reflection
.nil?
272 raise HasManyThroughAssociationNotFoundError
.new(active_record
.name
, self)
275 if source_reflection
.nil?
276 raise HasManyThroughSourceAssociationNotFoundError
.new(self)
279 if options
[:source_type] && source_reflection
.options
[:polymorphic].nil?
280 raise HasManyThroughAssociationPointlessSourceTypeError
.new(active_record
.name
, self, source_reflection
)
283 if source_reflection
.options
[:polymorphic] && options
[:source_type].nil?
284 raise HasManyThroughAssociationPolymorphicError
.new(active_record
.name
, self, source_reflection
)
287 unless [:belongs_to, :has_many].include?(source_reflection
.macro
) && source_reflection
.options
[:through].nil?
288 raise HasManyThroughSourceAssociationMacroError
.new(self)
292 def through_reflection_primary_key
293 through_reflection
.belongs_to
? ? through_reflection
.klass
.primary_key
: through_reflection
.primary_key_name
296 def through_reflection_primary_key_name
297 through_reflection
.primary_key_name
if through_reflection
.belongs_to
?
301 def derive_class_name
302 # get the class_name of the belongs_to association of the through reflection
303 options
[:source_type] || source_reflection
.class_name