2 require 'active_support/core_ext/module/attribute_accessors'
3 require 'active_support/core_ext/load_error'
4 require 'active_support/core_ext/kernel'
6 module Dependencies #:nodoc:
9 # Should we turn on Ruby warnings on the first load of dependent files?
10 mattr_accessor :warnings_on_first_load
11 self.warnings_on_first_load = false
13 # All files ever loaded.
14 mattr_accessor :history
15 self.history = Set.new
17 # All files currently loaded.
18 mattr_accessor :loaded
21 # Should we load files or require them?
22 mattr_accessor :mechanism
23 self.mechanism = :load
25 # The set of directories from which we may automatically load files. Files
26 # under these directories will be reloaded on each request in development mode,
27 # unless the directory also appears in load_once_paths.
28 mattr_accessor :load_paths
31 # The set of directories from which automatically loaded constants are loaded
32 # only once. All directories in this set must also be present in +load_paths+.
33 mattr_accessor :load_once_paths
34 self.load_once_paths = []
36 # An array of qualified constant names that have been loaded. Adding a name to
37 # this array will cause it to be unloaded the next time Dependencies are cleared.
38 mattr_accessor :autoloaded_constants
39 self.autoloaded_constants = []
41 # An array of constant names that need to be unloaded on every request. Used
42 # to allow arbitrary constants to be marked for unloading.
43 mattr_accessor :explicitly_unloadable_constants
44 self.explicitly_unloadable_constants = []
46 # Set to true to enable logging of const_missing and file loads
47 mattr_accessor :log_activity
48 self.log_activity = false
50 # An internal stack used to record which constants are loaded by any block.
51 mattr_accessor :constant_watch_stack
52 self.constant_watch_stack = []
58 def depend_on(file_name, swallow_load_errors = false)
59 path = search_for_file(file_name)
60 require_or_load(path || file_name)
62 raise unless swallow_load_errors
65 def associate_with(file_name)
66 depend_on(file_name, true)
72 remove_unloadable_constants!
75 def require_or_load(file_name, const_path = nil)
76 log_call file_name, const_path
77 file_name = $1 if file_name =~ /^(.*)\.rb$/
78 expanded = File.expand_path(file_name)
79 return if loaded.include?(expanded)
81 # Record that we've seen this file *before* loading it to avoid an
82 # infinite loop with mutual dependencies.
86 log "loading #{file_name}"
88 # Enable warnings iff this file has not been loaded before and
89 # warnings_on_first_load is set.
90 load_args = ["#{file_name}.rb"]
91 load_args << const_path unless const_path.nil?
93 if !warnings_on_first_load or history.include?(expanded)
94 result = load_file(*load_args)
96 enable_warnings { result = load_file(*load_args) }
99 loaded.delete expanded
103 log "requiring #{file_name}"
104 result = require file_name
107 # Record history *after* loading so first load gets warnings.
112 # Is the provided constant path defined?
113 def qualified_const_defined?(path)
114 raise NameError, "#{path.inspect} is not a valid constant name!" unless
115 /^(::)?([A-Z]\w*)(::[A-Z]\w*)*$/ =~ path
117 names = path.to_s.split('::')
118 names.shift if names.first.empty?
120 # We can't use defined? because it will invoke const_missing for the parent
121 # of the name we are checking.
122 names.inject(Object) do |mod, name|
123 return false unless mod.const_defined? name
129 # Given +path+, a filesystem path to a ruby file, return an array of constant
130 # paths which would cause Dependencies to attempt to load this file.
132 def loadable_constants_for_path(path, bases = load_paths)
133 path = $1 if path =~ /\A(.*)\.rb\Z/
134 expanded_path = File.expand_path(path)
136 bases.collect do |root|
137 expanded_root = File.expand_path(root)
138 next unless %r{\A#{Regexp.escape(expanded_root)}(/|\\)} =~ expanded_path
140 nesting = expanded_path[(expanded_root.size)..-1]
141 nesting = nesting[1..-1] if nesting && nesting[0] == ?/
142 next if nesting.blank?
146 # Special case: application.rb might define ApplicationControlller.
147 ('ApplicationController' if nesting == 'application')
149 end.flatten.compact.uniq
152 # Search for a file in load_paths matching the provided suffix.
153 def search_for_file(path_suffix)
154 path_suffix = path_suffix + '.rb' unless path_suffix.ends_with? '.rb'
155 load_paths.each do |root|
156 path = File.join(root, path_suffix)
157 return path if File.file? path
159 nil # Gee, I sure wish we had first_match ;-)
162 # Does the provided path_suffix correspond to an autoloadable module?
163 # Instead of returning a boolean, the autoload base for this module is returned.
164 def autoloadable_module?(path_suffix)
165 load_paths.each do |load_path|
166 return load_path if File.directory? File.join(load_path, path_suffix)
171 def load_once_path?(path)
172 load_once_paths.any? { |base| path.starts_with? base }
175 # Attempt to autoload the provided module name by searching for a directory
176 # matching the expect path suffix. If found, the module is created and assigned
177 # to +into+'s constants with the name +const_name+. Provided that the directory
178 # was loaded from a reloadable base path, it is added to the set of constants
179 # that are to be unloaded.
180 def autoload_module!(into, const_name, qualified_name, path_suffix)
181 return nil unless base_path = autoloadable_module?(path_suffix)
183 into.const_set const_name, mod
184 autoloaded_constants << qualified_name unless load_once_paths.include?(base_path)
188 # Load the file at the provided path. +const_paths+ is a set of qualified
189 # constant names. When loading the file, Dependencies will watch for the
190 # addition of these constants. Each that is defined will be marked as
191 # autoloaded, and will be removed when Dependencies.clear is next called.
193 # If the second parameter is left off, then Dependencies will construct a set
194 # of names that the file at +path+ may define. See
195 # +loadable_constants_for_path+ for more details.
196 def load_file(path, const_paths = loadable_constants_for_path(path))
197 log_call path, const_paths
198 const_paths = [const_paths].compact unless const_paths.is_a? Array
199 parent_paths = const_paths.collect { |const_path| /(.*)::[^:]+\Z/ =~ const_path ? $1 : :Object }
202 newly_defined_paths = new_constants_in(*parent_paths) do
203 result = load_without_new_constant_marking path
206 autoloaded_constants.concat newly_defined_paths unless load_once_path?(path)
207 autoloaded_constants.uniq!
208 log "loading #{path} defined #{newly_defined_paths * ', '}" unless newly_defined_paths.empty?
212 # Return the constant path for the provided parent and constant name.
213 def qualified_name_for(mod, name)
214 mod_name = to_constant_name mod
215 (%w(Object Kernel).include? mod_name) ? name.to_s : "#{mod_name}::#{name}"
218 # Load the constant named +const_name+ which is missing from +from_mod+. If
219 # it is not possible to laod the constant into from_mod, try its parent module
220 # using const_missing.
221 def load_missing_constant(from_mod, const_name)
222 log_call from_mod, const_name
223 if from_mod == Kernel
224 if ::Object.const_defined?(const_name)
225 log "Returning Object::#{const_name} for Kernel::#{const_name}"
226 return ::Object.const_get(const_name)
228 log "Substituting Object for Kernel"
233 # If we have an anonymous module, all we can do is attempt to load from Object.
234 from_mod = Object if from_mod.name.blank?
236 unless qualified_const_defined?(from_mod.name) && from_mod.name.constantize.object_id == from_mod.object_id
237 raise ArgumentError, "A copy of #{from_mod} has been removed from the module tree but is still active!"
240 raise ArgumentError, "#{from_mod} is not missing constant #{const_name}!" if from_mod.const_defined?(const_name)
242 qualified_name = qualified_name_for from_mod, const_name
243 path_suffix = qualified_name.underscore
244 name_error = NameError.new("uninitialized constant #{qualified_name}")
246 file_path = search_for_file(path_suffix)
247 if file_path && ! loaded.include?(File.expand_path(file_path)) # We found a matching file to load
248 require_or_load file_path
249 raise LoadError, "Expected #{file_path} to define #{qualified_name}" unless from_mod.const_defined?(const_name)
250 return from_mod.const_get(const_name)
251 elsif mod = autoload_module!(from_mod, const_name, qualified_name, path_suffix)
253 elsif (parent = from_mod.parent) && parent != from_mod &&
254 ! from_mod.parents.any? { |p| p.const_defined?(const_name) }
255 # If our parents do not have a constant named +const_name+ then we are free
256 # to attempt to load upwards. If they do have such a constant, then this
257 # const_missing must be due to from_mod::const_name, which should not
258 # return constants from from_mod's parents.
260 return parent.const_missing(const_name)
261 rescue NameError => e
262 raise unless e.missing_name? qualified_name_for(parent, const_name)
270 # Remove the constants that have been autoloaded, and those that have been
271 # marked for unloading.
272 def remove_unloadable_constants!
273 autoloaded_constants.each { |const| remove_constant const }
274 autoloaded_constants.clear
275 explicitly_unloadable_constants.each { |const| remove_constant const }
278 # Determine if the given constant has been automatically loaded.
279 def autoloaded?(desc)
280 # No name => anonymous module.
281 return false if desc.is_a?(Module) && desc.name.blank?
282 name = to_constant_name desc
283 return false unless qualified_const_defined? name
284 return autoloaded_constants.include?(name)
287 # Will the provided constant descriptor be unloaded?
288 def will_unload?(const_desc)
290 explicitly_unloadable_constants.include?(to_constant_name(const_desc))
293 # Mark the provided constant name for unloading. This constant will be
294 # unloaded on each request, not just the next one.
295 def mark_for_unload(const_desc)
296 name = to_constant_name const_desc
297 if explicitly_unloadable_constants.include? name
300 explicitly_unloadable_constants << name
305 # Run the provided block and detect the new constants that were loaded during
306 # its execution. Constants may only be regarded as 'new' once -- so if the
307 # block calls +new_constants_in+ again, then the constants defined within the
308 # inner call will not be reported in this one.
310 # If the provided block does not run to completion, and instead raises an
311 # exception, any new constants are regarded as being only partially defined
312 # and will be removed immediately.
313 def new_constants_in(*descs)
316 # Build the watch frames. Each frame is a tuple of
317 # [module_name_as_string, constants_defined_elsewhere]
318 watch_frames = descs.collect do |desc|
321 initial_constants = desc.local_constants
322 elsif desc.is_a?(String) || desc.is_a?(Symbol)
325 # Handle the case where the module has yet to be defined.
326 initial_constants = if qualified_const_defined?(mod_name)
327 mod_name.constantize.local_constants
332 raise Argument, "#{desc.inspect} does not describe a module!"
335 [mod_name, initial_constants]
338 constant_watch_stack.concat watch_frames
342 yield # Now yield to the code that is to define new constants.
345 # Find the new constants.
346 new_constants = watch_frames.collect do |mod_name, prior_constants|
347 # Module still doesn't exist? Treat it as if it has no constants.
348 next [] unless qualified_const_defined?(mod_name)
350 mod = mod_name.constantize
351 next [] unless mod.is_a? Module
352 new_constants = mod.local_constants - prior_constants
354 # Make sure no other frames takes credit for these constants.
355 constant_watch_stack.each do |frame_name, constants|
356 constants.concat new_constants if frame_name == mod_name
359 new_constants.collect do |suffix|
360 mod_name == "Object" ? suffix : "#{mod_name}::#{suffix}"
364 log "New constants: #{new_constants * ', '}"
367 log "Error during loading, removing partially loaded constants "
368 new_constants.each { |name| remove_constant name }
375 # Remove the stack frames that we added.
376 if defined?(watch_frames) && ! watch_frames.empty?
377 frame_ids = watch_frames.collect(&:object_id)
378 constant_watch_stack.delete_if do |watch_frame|
379 frame_ids.include? watch_frame.object_id
384 class LoadingModule #:nodoc:
385 # Old style environment.rb referenced this method directly. Please note, it doesn't
386 # actually *do* anything any more.
388 if defined?(RAILS_DEFAULT_LOGGER)
389 RAILS_DEFAULT_LOGGER.warn "Your environment.rb uses the old syntax, it may not continue to work in future releases."
390 RAILS_DEFAULT_LOGGER.warn "For upgrade instructions please see: http://manuals.rubyonrails.com/read/book/19"
395 # Convert the provided const desc to a qualified constant name (as a string).
396 # A module, class, symbol, or string may be provided.
397 def to_constant_name(desc) #:nodoc:
399 when String then desc.starts_with?('::') ? desc[2..-1] : desc
400 when Symbol then desc.to_s
402 raise ArgumentError, "Anonymous modules have no name to be referenced by" if desc.name.blank?
404 else raise TypeError, "Not a valid constant descriptor: #{desc.inspect}"
408 def remove_constant(const) #:nodoc:
409 return false unless qualified_const_defined? const
411 const = $1 if /\A::(.*)\Z/ =~ const.to_s
412 names = const.to_s.split('::')
413 if names.size == 1 # It's under Object
416 parent = (names[0..-2] * '::').constantize
419 log "removing constant #{const}"
420 parent.instance_eval { remove_const names.last }
426 arg_str = args.collect(&:inspect) * ', '
427 /in `([a-z_\?\!]+)'/ =~ caller(1).first
428 selector = $1 || '<unknown>'
429 log "called #{selector}(#{arg_str})"
433 if defined?(RAILS_DEFAULT_LOGGER) && RAILS_DEFAULT_LOGGER && log_activity
434 RAILS_DEFAULT_LOGGER.debug "Dependencies: #{msg}"
440 Object.instance_eval do
441 define_method(:require_or_load) { |file_name| Dependencies.require_or_load(file_name) } unless Object.respond_to?(:require_or_load)
442 define_method(:require_dependency) { |file_name| Dependencies.depend_on(file_name) } unless Object.respond_to?(:require_dependency)
443 define_method(:require_association) { |file_name| Dependencies.associate_with(file_name) } unless Object.respond_to?(:require_association)
446 class Module #:nodoc:
447 # Rename the original handler so we can chain it to the new one
448 alias :rails_original_const_missing :const_missing
450 # Use const_missing to autoload associations so we don't have to
451 # require_association when using single-table inheritance.
452 def const_missing(class_id)
453 Dependencies.load_missing_constant self, class_id
456 def unloadable(const_desc = self)
463 def const_missing(class_id)
464 if [Object, Kernel].include?(self) || parent == self
469 Dependencies.load_missing_constant self, class_id
471 parent.send :const_missing, class_id
473 rescue NameError => e
474 # Make sure that the name we are missing is the one that caused the error
475 parent_qualified_name = Dependencies.qualified_name_for parent, class_id
476 raise unless e.missing_name? parent_qualified_name
477 qualified_name = Dependencies.qualified_name_for self, class_id
478 raise NameError.new("uninitialized constant #{qualified_name}").copy_blame!(e)
486 alias_method :load_without_new_constant_marking, :load
488 def load(file, *extras) #:nodoc:
489 Dependencies.new_constants_in(Object) { super(file, *extras) }
490 rescue Exception => exception # errors from loading file
491 exception.blame_file! file
495 def require(file, *extras) #:nodoc:
496 Dependencies.new_constants_in(Object) { super(file, *extras) }
497 rescue Exception => exception # errors from required file
498 exception.blame_file! file
502 # Mark the given constant as unloadable. Unloadable constants are removed each
503 # time dependencies are cleared.
505 # Note that marking a constant for unloading need only be done once. Setup
506 # or init scripts may list each unloadable constant that may need unloading;
507 # each constant will be removed for every subsequent clear, as opposed to for
510 # The provided constant descriptor may be a (non-anonymous) module or class,
511 # or a qualified constant name as a string or symbol.
513 # Returns true if the constant was not previously marked for unloading, false
515 def unloadable(const_desc)
516 Dependencies.mark_for_unload const_desc
521 # Add file-blaming to exceptions
522 class Exception #:nodoc:
523 def blame_file!(file)
524 (@blamed_files ||= []).unshift file
532 return nil if blamed_files.empty?
533 "This error occurred while loading the following files:\n #{blamed_files.join "\n "}"
537 @blamed_files = exc.blamed_files.clone