PageRenderTime 84ms CodeModel.GetById 30ms RepoModel.GetById 0ms app.codeStats 1ms

/External.LCA_RESTRICTED/Languages/Ruby/ruby19/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0/lib/active_support/dependencies.rb

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