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
69 # Returns an array of AssociationReflection objects for all associations which have <tt>:autosave</tt> enabled.
70 def reflect_on_all_autosave_associations
71 reflections
.values
.select
{ |reflection
| reflection
.options
[:autosave] }
76 # Abstract base class for AggregateReflection and AssociationReflection that describes the interface available for both of
77 # those classes. Objects of AggregateReflection and AssociationReflection are returned by the Reflection::ClassMethods.
79 attr_reader
:active_record
81 def initialize(macro
, name
, options
, active_record
)
82 @macro, @name, @options, @active_record = macro
, name
, options
, active_record
85 # Returns the name of the macro. For example, <tt>composed_of :balance, :class_name => 'Money'</tt> will return
86 # <tt>:balance</tt> or for <tt>has_many :clients</tt> it will return <tt>:clients</tt>.
91 # Returns the macro type. For example, <tt>composed_of :balance, :class_name => 'Money'</tt> will return <tt>:composed_of</tt>
92 # or for <tt>has_many :clients</tt> will return <tt>:has_many</tt>.
97 # Returns the hash of options used for the macro. For example, it would return <tt>{ :class_name => "Money" }</tt> for
98 # <tt>composed_of :balance, :class_name => 'Money'</tt> or +{}+ for <tt>has_many :clients</tt>.
103 # Returns the class for the macro. For example, <tt>composed_of :balance, :class_name => 'Money'</tt> returns the Money
104 # class and <tt>has_many :clients</tt> returns the Client class.
106 @klass ||= class_name
.constantize
109 # Returns the class name for the macro. For example, <tt>composed_of :balance, :class_name => 'Money'</tt> returns <tt>'Money'</tt>
110 # and <tt>has_many :clients</tt> returns <tt>'Client'</tt>.
112 @class_name ||= options
[:class_name] || derive_class_name
115 # Returns +true+ if +self+ and +other_aggregation+ have the same +name+ attribute, +active_record+ attribute,
116 # and +other_aggregation+ has an options hash assigned to it.
117 def ==(other_aggregation
)
118 other_aggregation
.kind_of
?(self.class) && name
== other_aggregation
.name
&& other_aggregation
.options
&& active_record
== other_aggregation
.active_record
121 def sanitized_conditions
#:nodoc:
122 @sanitized_conditions ||= klass
.send(:sanitize_sql, options
[:conditions]) if options
[:conditions]
125 # Returns +true+ if +self+ is a +belongs_to+ reflection.
131 def derive_class_name
137 # Holds all the meta-data about an aggregation as it was specified in the Active Record class.
138 class AggregateReflection
< MacroReflection
#:nodoc:
141 # Holds all the meta-data about an association as it was specified in the Active Record class.
142 class AssociationReflection
< MacroReflection
#:nodoc:
143 # Returns the target association's class:
145 # class Author < ActiveRecord::Base
149 # Author.reflect_on_association(:books).klass
152 # <b>Note:</b> do not call +klass.new+ or +klass.create+ to instantiate
153 # a new association object. Use +build_association+ or +create_association+
154 # instead. This allows plugins to hook into association object creation.
156 @klass ||= active_record
.send(:compute_type, class_name
)
159 # Returns a new, unsaved instance of the associated class. +options+ will
160 # be passed to the class's constructor.
161 def build_association(*options
)
165 # Creates a new instance of the associated class, and immediates saves it
166 # with ActiveRecord::Base#save. +options+ will be passed to the class's
167 # creation method. Returns the newly created object.
168 def create_association(*options
)
169 klass
.create(*options
)
172 # Creates a new instance of the associated class, and immediates saves it
173 # with ActiveRecord::Base#save!. +options+ will be passed to the class's
174 # creation method. If the created record doesn't pass validations, then an
175 # exception will be raised.
177 # Returns the newly created object.
178 def create_association
!(*options
)
179 klass
.create
!(*options
)
183 @table_name ||= klass
.table_name
186 def quoted_table_name
187 @quoted_table_name ||= klass
.quoted_table_name
191 @primary_key_name ||= options
[:foreign_key] || derive_primary_key_name
194 def association_foreign_key
195 @association_foreign_key ||= @options[:association_foreign_key] || class_name
.foreign_key
198 def counter_cache_column
199 if options
[:counter_cache] == true
200 "#{active_record.name.demodulize.underscore.pluralize}_count"
201 elsif options
[:counter_cache]
202 options
[:counter_cache]
206 def columns(tbl_name
, log_msg
)
207 @columns ||= klass
.connection
.columns(tbl_name
, log_msg
)
210 def reset_column_information
217 def through_reflection
221 def through_reflection_primary_key_name
224 def source_reflection
229 def derive_class_name
230 class_name
= name
.to_s
.camelize
231 class_name
= class_name
.singularize
if [ :has_many, :has_and_belongs_to_many ].include?(macro
)
235 def derive_primary_key_name
241 active_record
.name
.foreign_key
246 # Holds all the meta-data about a :through association as it was specified in the Active Record class.
247 class ThroughReflection
< AssociationReflection
#:nodoc:
248 # 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>.
249 # (The <tt>:tags</tt> association on Tagging below.)
251 # class Post < ActiveRecord::Base
253 # has_many :tags, :through => :taggings
256 def source_reflection
257 @source_reflection ||= source_reflection_names
.collect
{ |name
| through_reflection
.klass
.reflect_on_association(name
) }.compact
.first
260 # Returns the AssociationReflection object specified in the <tt>:through</tt> option
261 # of a HasManyThrough or HasOneThrough association. Example:
263 # class Post < ActiveRecord::Base
265 # has_many :tags, :through => :taggings
268 # tags_reflection = Post.reflect_on_association(:tags)
269 # taggings_reflection = tags_reflection.through_reflection
271 def through_reflection
272 @through_reflection ||= active_record
.reflect_on_association(options
[:through])
275 # Gets an array of possible <tt>:through</tt> source reflection names:
277 # [:singularized, :pluralized]
279 def source_reflection_names
280 @source_reflection_names ||= (options
[:source] ? [options
[:source]] : [name
.to_s
.singularize
, name
]).collect
{ |n
| n
.to_sym
}
284 if through_reflection
.nil?
285 raise HasManyThroughAssociationNotFoundError
.new(active_record
.name
, self)
288 if source_reflection
.nil?
289 raise HasManyThroughSourceAssociationNotFoundError
.new(self)
292 if options
[:source_type] && source_reflection
.options
[:polymorphic].nil?
293 raise HasManyThroughAssociationPointlessSourceTypeError
.new(active_record
.name
, self, source_reflection
)
296 if source_reflection
.options
[:polymorphic] && options
[:source_type].nil?
297 raise HasManyThroughAssociationPolymorphicError
.new(active_record
.name
, self, source_reflection
)
300 unless [:belongs_to, :has_many].include?(source_reflection
.macro
) && source_reflection
.options
[:through].nil?
301 raise HasManyThroughSourceAssociationMacroError
.new(self)
305 def through_reflection_primary_key
306 through_reflection
.belongs_to
? ? through_reflection
.klass
.primary_key
: through_reflection
.primary_key_name
309 def through_reflection_primary_key_name
310 through_reflection
.primary_key_name
if through_reflection
.belongs_to
?
314 def derive_class_name
315 # get the class_name of the belongs_to association of the through reflection
316 options
[:source_type] || source_reflection
.class_name