PageRenderTime 34ms CodeModel.GetById 8ms RepoModel.GetById 0ms app.codeStats 0ms

/activesupport/lib/active_support/dependencies.rb

https://github.com/ghar/rails
Ruby | 682 lines | 443 code | 109 blank | 130 comment | 37 complexity | 52029d2928f7352b9516aa0f21fa9d77 MD5 | raw file
  1. require 'set'
  2. require 'thread'
  3. require 'pathname'
  4. require 'active_support/core_ext/module/aliasing'
  5. require 'active_support/core_ext/module/attribute_accessors'
  6. require 'active_support/core_ext/module/introspection'
  7. require 'active_support/core_ext/module/anonymous'
  8. require 'active_support/core_ext/object/blank'
  9. require 'active_support/core_ext/load_error'
  10. require 'active_support/core_ext/name_error'
  11. require 'active_support/core_ext/string/starts_ends_with'
  12. require 'active_support/inflector'
  13. module ActiveSupport #:nodoc:
  14. module Dependencies #:nodoc:
  15. extend self
  16. # Should we turn on Ruby warnings on the first load of dependent files?
  17. mattr_accessor :warnings_on_first_load
  18. self.warnings_on_first_load = false
  19. # All files ever loaded.
  20. mattr_accessor :history
  21. self.history = Set.new
  22. # All files currently loaded.
  23. mattr_accessor :loaded
  24. self.loaded = Set.new
  25. # Should we load files or require them?
  26. mattr_accessor :mechanism
  27. self.mechanism = ENV['NO_RELOAD'] ? :require : :load
  28. # The set of directories from which we may automatically load files. Files
  29. # under these directories will be reloaded on each request in development mode,
  30. # unless the directory also appears in autoload_once_paths.
  31. mattr_accessor :autoload_paths
  32. self.autoload_paths = []
  33. # The set of directories from which automatically loaded constants are loaded
  34. # only once. All directories in this set must also be present in +autoload_paths+.
  35. mattr_accessor :autoload_once_paths
  36. self.autoload_once_paths = []
  37. # An array of qualified constant names that have been loaded. Adding a name to
  38. # this array will cause it to be unloaded the next time Dependencies are cleared.
  39. mattr_accessor :autoloaded_constants
  40. 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 = []
  45. # The logger is used for generating information on the action run-time (including benchmarking) if available.
  46. # Can be set to nil for no logging. Compatible with both Ruby's own Logger and Log4r loggers.
  47. mattr_accessor :logger
  48. # Set to true to enable logging of const_missing and file loads
  49. mattr_accessor :log_activity
  50. self.log_activity = false
  51. # The WatchStack keeps a stack of the modules being watched as files are loaded.
  52. # If a file in the process of being loaded (parent.rb) triggers the load of
  53. # another file (child.rb) the stack will ensure that child.rb handles the new
  54. # constants.
  55. #
  56. # If child.rb is being autoloaded, its constants will be added to
  57. # autoloaded_constants. If it was being `require`d, they will be discarded.
  58. #
  59. # This is handled by walking back up the watch stack and adding the constants
  60. # found by child.rb to the list of original constants in parent.rb
  61. class WatchStack < Hash
  62. # @watching is a stack of lists of constants being watched. For instance,
  63. # if parent.rb is autoloaded, the stack will look like [[Object]]. If parent.rb
  64. # then requires namespace/child.rb, the stack will look like [[Object], [Namespace]].
  65. def initialize
  66. @watching = []
  67. super { |h,k| h[k] = [] }
  68. end
  69. # return a list of new constants found since the last call to watch_namespaces
  70. def new_constants
  71. constants = []
  72. # Grab the list of namespaces that we're looking for new constants under
  73. @watching.last.each do |namespace|
  74. # Retrieve the constants that were present under the namespace when watch_namespaces
  75. # was originally called
  76. original_constants = self[namespace].last
  77. mod = Inflector.constantize(namespace) if Dependencies.qualified_const_defined?(namespace)
  78. next unless mod.is_a?(Module)
  79. # Get a list of the constants that were added
  80. new_constants = mod.local_constant_names - original_constants
  81. # self[namespace] returns an Array of the constants that are being evaluated
  82. # for that namespace. For instance, if parent.rb requires child.rb, the first
  83. # element of self[Object] will be an Array of the constants that were present
  84. # before parent.rb was required. The second element will be an Array of the
  85. # constants that were present before child.rb was required.
  86. self[namespace].each do |namespace_constants|
  87. namespace_constants.concat(new_constants)
  88. end
  89. # Normalize the list of new constants, and add them to the list we will return
  90. new_constants.each do |suffix|
  91. constants << ([namespace, suffix] - ["Object"]).join("::")
  92. end
  93. end
  94. constants
  95. ensure
  96. # A call to new_constants is always called after a call to watch_namespaces
  97. pop_modules(@watching.pop)
  98. end
  99. # Add a set of modules to the watch stack, remembering the initial constants
  100. def watch_namespaces(namespaces)
  101. watching = []
  102. namespaces.map do |namespace|
  103. module_name = Dependencies.to_constant_name(namespace)
  104. original_constants = Dependencies.qualified_const_defined?(module_name) ?
  105. Inflector.constantize(module_name).local_constant_names : []
  106. watching << module_name
  107. self[module_name] << original_constants
  108. end
  109. @watching << watching
  110. end
  111. def pop_modules(modules)
  112. modules.each { |mod| self[mod].pop }
  113. end
  114. end
  115. # An internal stack used to record which constants are loaded by any block.
  116. mattr_accessor :constant_watch_stack
  117. self.constant_watch_stack = WatchStack.new
  118. # Module includes this module
  119. module ModuleConstMissing #:nodoc:
  120. def self.append_features(base)
  121. base.class_eval do
  122. # Emulate #exclude via an ivar
  123. return if defined?(@_const_missing) && @_const_missing
  124. @_const_missing = instance_method(:const_missing)
  125. remove_method(:const_missing)
  126. end
  127. super
  128. end
  129. def self.exclude_from(base)
  130. base.class_eval do
  131. define_method :const_missing, @_const_missing
  132. @_const_missing = nil
  133. end
  134. end
  135. # Use const_missing to autoload associations so we don't have to
  136. # require_association when using single-table inheritance.
  137. def const_missing(const_name, nesting = nil)
  138. klass_name = name.presence || "Object"
  139. unless nesting
  140. # We'll assume that the nesting of Foo::Bar is ["Foo::Bar", "Foo"]
  141. # even though it might not be, such as in the case of
  142. # class Foo::Bar; Baz; end
  143. nesting = []
  144. klass_name.to_s.scan(/::|$/) { nesting.unshift $` }
  145. end
  146. # If there are multiple levels of nesting to search under, the top
  147. # level is the one we want to report as the lookup fail.
  148. error = nil
  149. nesting.each do |namespace|
  150. begin
  151. return Dependencies.load_missing_constant Inflector.constantize(namespace), const_name
  152. rescue NoMethodError then raise
  153. rescue NameError => e
  154. error ||= e
  155. end
  156. end
  157. # Raise the first error for this set. If this const_missing came from an
  158. # earlier const_missing, this will result in the real error bubbling
  159. # all the way up
  160. raise error
  161. end
  162. def unloadable(const_desc = self)
  163. super(const_desc)
  164. end
  165. end
  166. # Object includes this module
  167. module Loadable #:nodoc:
  168. def self.exclude_from(base)
  169. base.class_eval { define_method(:load, Kernel.instance_method(:load)) }
  170. end
  171. def require_or_load(file_name)
  172. Dependencies.require_or_load(file_name)
  173. end
  174. def require_dependency(file_name, message = "No such file to load -- %s")
  175. unless file_name.is_a?(String)
  176. raise ArgumentError, "the file name must be a String -- you passed #{file_name.inspect}"
  177. end
  178. Dependencies.depend_on(file_name, false, message)
  179. end
  180. def require_association(file_name)
  181. Dependencies.associate_with(file_name)
  182. end
  183. def load_dependency(file)
  184. if Dependencies.load?
  185. Dependencies.new_constants_in(Object) { yield }.presence
  186. else
  187. yield
  188. end
  189. rescue Exception => exception # errors from loading file
  190. exception.blame_file! file
  191. raise
  192. end
  193. def load(file, *)
  194. result = false
  195. load_dependency(file) { result = super }
  196. result
  197. end
  198. def require(file, *)
  199. result = false
  200. load_dependency(file) { result = super }
  201. result
  202. end
  203. # Mark the given constant as unloadable. Unloadable constants are removed each
  204. # time dependencies are cleared.
  205. #
  206. # Note that marking a constant for unloading need only be done once. Setup
  207. # or init scripts may list each unloadable constant that may need unloading;
  208. # each constant will be removed for every subsequent clear, as opposed to for
  209. # the first clear.
  210. #
  211. # The provided constant descriptor may be a (non-anonymous) module or class,
  212. # or a qualified constant name as a string or symbol.
  213. #
  214. # Returns true if the constant was not previously marked for unloading, false
  215. # otherwise.
  216. def unloadable(const_desc)
  217. Dependencies.mark_for_unload const_desc
  218. end
  219. end
  220. # Exception file-blaming
  221. module Blamable #:nodoc:
  222. def blame_file!(file)
  223. (@blamed_files ||= []).unshift file
  224. end
  225. def blamed_files
  226. @blamed_files ||= []
  227. end
  228. def describe_blame
  229. return nil if blamed_files.empty?
  230. "This error occurred while loading the following files:\n #{blamed_files.join "\n "}"
  231. end
  232. def copy_blame!(exc)
  233. @blamed_files = exc.blamed_files.clone
  234. self
  235. end
  236. end
  237. def hook!
  238. Object.class_eval { include Loadable }
  239. Module.class_eval { include ModuleConstMissing }
  240. Exception.class_eval { include Blamable }
  241. true
  242. end
  243. def unhook!
  244. ModuleConstMissing.exclude_from(Module)
  245. Loadable.exclude_from(Object)
  246. true
  247. end
  248. def load?
  249. mechanism == :load
  250. end
  251. def depend_on(file_name, swallow_load_errors = false, message = "No such file to load -- %s.rb")
  252. path = search_for_file(file_name)
  253. require_or_load(path || file_name)
  254. rescue LoadError => load_error
  255. unless swallow_load_errors
  256. if file_name = load_error.message[/ -- (.*?)(\.rb)?$/, 1]
  257. raise LoadError.new(message % file_name).copy_blame!(load_error)
  258. end
  259. raise
  260. end
  261. end
  262. def associate_with(file_name)
  263. depend_on(file_name, true)
  264. end
  265. def clear
  266. log_call
  267. loaded.clear
  268. remove_unloadable_constants!
  269. end
  270. def require_or_load(file_name, const_path = nil)
  271. log_call file_name, const_path
  272. file_name = $1 if file_name =~ /^(.*)\.rb$/
  273. expanded = File.expand_path(file_name)
  274. return if loaded.include?(expanded)
  275. # Record that we've seen this file *before* loading it to avoid an
  276. # infinite loop with mutual dependencies.
  277. loaded << expanded
  278. begin
  279. if load?
  280. log "loading #{file_name}"
  281. # Enable warnings if this file has not been loaded before and
  282. # warnings_on_first_load is set.
  283. load_args = ["#{file_name}.rb"]
  284. load_args << const_path unless const_path.nil?
  285. if !warnings_on_first_load or history.include?(expanded)
  286. result = load_file(*load_args)
  287. else
  288. enable_warnings { result = load_file(*load_args) }
  289. end
  290. else
  291. log "requiring #{file_name}"
  292. result = require file_name
  293. end
  294. rescue Exception
  295. loaded.delete expanded
  296. raise
  297. end
  298. # Record history *after* loading so first load gets warnings.
  299. history << expanded
  300. return result
  301. end
  302. # Is the provided constant path defined?
  303. def qualified_const_defined?(path)
  304. names = path.sub(/^::/, '').to_s.split('::')
  305. names.inject(Object) do |mod, name|
  306. return false unless local_const_defined?(mod, name)
  307. mod.const_get name
  308. end
  309. end
  310. if Module.method(:const_defined?).arity == 1
  311. # Does this module define this constant?
  312. # Wrapper to accommodate changing Module#const_defined? in Ruby 1.9
  313. def local_const_defined?(mod, const)
  314. mod.const_defined?(const)
  315. end
  316. else
  317. def local_const_defined?(mod, const) #:nodoc:
  318. mod.const_defined?(const, false)
  319. end
  320. end
  321. # Given +path+, a filesystem path to a ruby file, return an array of constant
  322. # paths which would cause Dependencies to attempt to load this file.
  323. def loadable_constants_for_path(path, bases = autoload_paths)
  324. path = $1 if path =~ /\A(.*)\.rb\Z/
  325. expanded_path = File.expand_path(path)
  326. paths = []
  327. bases.each do |root|
  328. expanded_root = File.expand_path(root)
  329. next unless %r{\A#{Regexp.escape(expanded_root)}(/|\\)} =~ expanded_path
  330. nesting = expanded_path[(expanded_root.size)..-1]
  331. nesting = nesting[1..-1] if nesting && nesting[0] == ?/
  332. next if nesting.blank?
  333. paths << nesting.camelize
  334. end
  335. paths.uniq!
  336. paths
  337. end
  338. # Search for a file in autoload_paths matching the provided suffix.
  339. def search_for_file(path_suffix)
  340. path_suffix = path_suffix.sub(/(\.rb)?$/, ".rb")
  341. autoload_paths.each do |root|
  342. path = File.join(root, path_suffix)
  343. return path if File.file? path
  344. end
  345. nil # Gee, I sure wish we had first_match ;-)
  346. end
  347. # Does the provided path_suffix correspond to an autoloadable module?
  348. # Instead of returning a boolean, the autoload base for this module is returned.
  349. def autoloadable_module?(path_suffix)
  350. autoload_paths.each do |load_path|
  351. return load_path if File.directory? File.join(load_path, path_suffix)
  352. end
  353. nil
  354. end
  355. def load_once_path?(path)
  356. # to_s works around a ruby1.9 issue where #starts_with?(Pathname) will always return false
  357. autoload_once_paths.any? { |base| path.starts_with? base.to_s }
  358. end
  359. # Attempt to autoload the provided module name by searching for a directory
  360. # matching the expect path suffix. If found, the module is created and assigned
  361. # to +into+'s constants with the name +const_name+. Provided that the directory
  362. # was loaded from a reloadable base path, it is added to the set of constants
  363. # that are to be unloaded.
  364. def autoload_module!(into, const_name, qualified_name, path_suffix)
  365. return nil unless base_path = autoloadable_module?(path_suffix)
  366. mod = Module.new
  367. into.const_set const_name, mod
  368. autoloaded_constants << qualified_name unless autoload_once_paths.include?(base_path)
  369. return mod
  370. end
  371. # Load the file at the provided path. +const_paths+ is a set of qualified
  372. # constant names. When loading the file, Dependencies will watch for the
  373. # addition of these constants. Each that is defined will be marked as
  374. # autoloaded, and will be removed when Dependencies.clear is next called.
  375. #
  376. # If the second parameter is left off, then Dependencies will construct a set
  377. # of names that the file at +path+ may define. See
  378. # +loadable_constants_for_path+ for more details.
  379. def load_file(path, const_paths = loadable_constants_for_path(path))
  380. log_call path, const_paths
  381. const_paths = [const_paths].compact unless const_paths.is_a? Array
  382. parent_paths = const_paths.collect { |const_path| /(.*)::[^:]+\Z/ =~ const_path ? $1 : :Object }
  383. result = nil
  384. newly_defined_paths = new_constants_in(*parent_paths) do
  385. result = Kernel.load path
  386. end
  387. autoloaded_constants.concat newly_defined_paths unless load_once_path?(path)
  388. autoloaded_constants.uniq!
  389. log "loading #{path} defined #{newly_defined_paths * ', '}" unless newly_defined_paths.empty?
  390. return result
  391. end
  392. # Return the constant path for the provided parent and constant name.
  393. def qualified_name_for(mod, name)
  394. mod_name = to_constant_name mod
  395. mod_name == "Object" ? name.to_s : "#{mod_name}::#{name}"
  396. end
  397. # Load the constant named +const_name+ which is missing from +from_mod+. If
  398. # it is not possible to load the constant into from_mod, try its parent module
  399. # using const_missing.
  400. def load_missing_constant(from_mod, const_name)
  401. log_call from_mod, const_name
  402. unless qualified_const_defined?(from_mod.name) && Inflector.constantize(from_mod.name).equal?(from_mod)
  403. raise ArgumentError, "A copy of #{from_mod} has been removed from the module tree but is still active!"
  404. end
  405. raise NameError, "#{from_mod} is not missing constant #{const_name}!" if local_const_defined?(from_mod, const_name)
  406. qualified_name = qualified_name_for from_mod, const_name
  407. path_suffix = qualified_name.underscore
  408. file_path = search_for_file(path_suffix)
  409. if file_path && ! loaded.include?(File.expand_path(file_path)) # We found a matching file to load
  410. require_or_load file_path
  411. raise LoadError, "Expected #{file_path} to define #{qualified_name}" unless local_const_defined?(from_mod, const_name)
  412. return from_mod.const_get(const_name)
  413. elsif mod = autoload_module!(from_mod, const_name, qualified_name, path_suffix)
  414. return mod
  415. elsif (parent = from_mod.parent) && parent != from_mod &&
  416. ! from_mod.parents.any? { |p| local_const_defined?(p, const_name) }
  417. # If our parents do not have a constant named +const_name+ then we are free
  418. # to attempt to load upwards. If they do have such a constant, then this
  419. # const_missing must be due to from_mod::const_name, which should not
  420. # return constants from from_mod's parents.
  421. begin
  422. return parent.const_missing(const_name)
  423. rescue NameError => e
  424. raise unless e.missing_name? qualified_name_for(parent, const_name)
  425. end
  426. end
  427. raise NameError,
  428. "uninitialized constant #{qualified_name}",
  429. caller.reject {|l| l.starts_with? __FILE__ }
  430. end
  431. # Remove the constants that have been autoloaded, and those that have been
  432. # marked for unloading. Before each constant is removed a callback is sent
  433. # to its class/module if it implements +before_remove_const+.
  434. #
  435. # The callback implementation should be restricted to cleaning up caches, etc.
  436. # as the environment will be in an inconsistent state, e.g. other constants
  437. # may have already been unloaded and not accessible.
  438. def remove_unloadable_constants!
  439. autoloaded_constants.each { |const| remove_constant const }
  440. autoloaded_constants.clear
  441. Reference.clear!
  442. explicitly_unloadable_constants.each { |const| remove_constant const }
  443. end
  444. class ClassCache
  445. def initialize
  446. @store = Hash.new { |h, k| h[k] = Inflector.constantize(k) }
  447. end
  448. def empty?
  449. @store.empty?
  450. end
  451. def key?(key)
  452. @store.key?(key)
  453. end
  454. def []=(key, value)
  455. return unless key.respond_to?(:name)
  456. raise(ArgumentError, 'anonymous classes cannot be cached') if key.name.blank?
  457. @store[key.name] = value
  458. end
  459. def [](key)
  460. key = key.name if key.respond_to?(:name)
  461. @store[key]
  462. end
  463. alias :get :[]
  464. def store(name)
  465. self[name] = name
  466. self
  467. end
  468. def clear!
  469. @store.clear
  470. end
  471. end
  472. Reference = ClassCache.new
  473. # Store a reference to a class +klass+.
  474. def reference(klass)
  475. Reference.store klass
  476. end
  477. # Get the reference for class named +name+.
  478. def constantize(name)
  479. Reference.get(name)
  480. end
  481. # Determine if the given constant has been automatically loaded.
  482. def autoloaded?(desc)
  483. # No name => anonymous module.
  484. return false if desc.is_a?(Module) && desc.anonymous?
  485. name = to_constant_name desc
  486. return false unless qualified_const_defined? name
  487. return autoloaded_constants.include?(name)
  488. end
  489. # Will the provided constant descriptor be unloaded?
  490. def will_unload?(const_desc)
  491. autoloaded?(const_desc) ||
  492. explicitly_unloadable_constants.include?(to_constant_name(const_desc))
  493. end
  494. # Mark the provided constant name for unloading. This constant will be
  495. # unloaded on each request, not just the next one.
  496. def mark_for_unload(const_desc)
  497. name = to_constant_name const_desc
  498. if explicitly_unloadable_constants.include? name
  499. return false
  500. else
  501. explicitly_unloadable_constants << name
  502. return true
  503. end
  504. end
  505. # Run the provided block and detect the new constants that were loaded during
  506. # its execution. Constants may only be regarded as 'new' once -- so if the
  507. # block calls +new_constants_in+ again, then the constants defined within the
  508. # inner call will not be reported in this one.
  509. #
  510. # If the provided block does not run to completion, and instead raises an
  511. # exception, any new constants are regarded as being only partially defined
  512. # and will be removed immediately.
  513. def new_constants_in(*descs)
  514. log_call(*descs)
  515. constant_watch_stack.watch_namespaces(descs)
  516. aborting = true
  517. begin
  518. yield # Now yield to the code that is to define new constants.
  519. aborting = false
  520. ensure
  521. new_constants = constant_watch_stack.new_constants
  522. log "New constants: #{new_constants * ', '}"
  523. return new_constants unless aborting
  524. log "Error during loading, removing partially loaded constants "
  525. new_constants.each {|c| remove_constant(c) }.clear
  526. end
  527. return []
  528. end
  529. # Convert the provided const desc to a qualified constant name (as a string).
  530. # A module, class, symbol, or string may be provided.
  531. def to_constant_name(desc) #:nodoc:
  532. case desc
  533. when String then desc.sub(/^::/, '')
  534. when Symbol then desc.to_s
  535. when Module
  536. desc.name.presence ||
  537. raise(ArgumentError, "Anonymous modules have no name to be referenced by")
  538. else raise TypeError, "Not a valid constant descriptor: #{desc.inspect}"
  539. end
  540. end
  541. def remove_constant(const) #:nodoc:
  542. return false unless qualified_const_defined? const
  543. # Normalize ::Foo, Foo, Object::Foo, and ::Object::Foo to Object::Foo
  544. names = const.to_s.sub(/^::(Object)?/, 'Object::').split("::")
  545. to_remove = names.pop
  546. parent = Inflector.constantize(names * '::')
  547. log "removing constant #{const}"
  548. constantized = constantize(const)
  549. constantized.before_remove_const if constantized.respond_to?(:before_remove_const)
  550. parent.instance_eval { remove_const to_remove }
  551. return true
  552. end
  553. protected
  554. def log_call(*args)
  555. if log_activity?
  556. arg_str = args.collect { |arg| arg.inspect } * ', '
  557. /in `([a-z_\?\!]+)'/ =~ caller(1).first
  558. selector = $1 || '<unknown>'
  559. log "called #{selector}(#{arg_str})"
  560. end
  561. end
  562. def log(msg)
  563. logger.debug "Dependencies: #{msg}" if log_activity?
  564. end
  565. def log_activity?
  566. logger && log_activity
  567. end
  568. end
  569. end
  570. ActiveSupport::Dependencies.hook!