From a6b39428431abeaa0251bbf4b6582e578f81783f Mon Sep 17 00:00:00 2001 From: wycats Date: Fri, 4 Jun 2010 17:28:04 -0700 Subject: Optimize LookupContext --- activesupport/lib/active_support/dependencies.rb | 23 +++++++++++++++++++++++ activesupport/test/dependencies_test.rb | 15 +++++++++++++++ 2 files changed, 38 insertions(+) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/dependencies.rb b/activesupport/lib/active_support/dependencies.rb index e14e225596..e0d2b70306 100644 --- a/activesupport/lib/active_support/dependencies.rb +++ b/activesupport/lib/active_support/dependencies.rb @@ -47,6 +47,9 @@ module ActiveSupport #:nodoc: mattr_accessor :autoloaded_constants self.autoloaded_constants = [] + mattr_accessor :references + self.references = {} + # An array of constant names that need to be unloaded on every request. Used # to allow arbitrary constants to be marked for unloading. mattr_accessor :explicitly_unloadable_constants @@ -476,9 +479,28 @@ module ActiveSupport #:nodoc: def remove_unloadable_constants! autoloaded_constants.each { |const| remove_constant const } autoloaded_constants.clear + references.each {|k,v| v.clear! } explicitly_unloadable_constants.each { |const| remove_constant const } end + class Reference + def initialize(constant, name) + @constant, @name = constant, name + end + + def get + @constant ||= Inflector.constantize(@name) + end + + def clear! + @constant = nil + end + end + + def ref(name) + references[name] ||= Reference.new(Inflector.constantize(name), name) + end + # Determine if the given constant has been automatically loaded. def autoloaded?(desc) # No name => anonymous module. @@ -572,6 +594,7 @@ module ActiveSupport #:nodoc: log "removing constant #{const}" parent.instance_eval { remove_const to_remove } + return true end diff --git a/activesupport/test/dependencies_test.rb b/activesupport/test/dependencies_test.rb index 75ff88505d..15543e07c3 100644 --- a/activesupport/test/dependencies_test.rb +++ b/activesupport/test/dependencies_test.rb @@ -431,6 +431,21 @@ class DependenciesTest < Test::Unit::TestCase end end + def test_references_should_work + with_loading 'dependencies' do + root = ActiveSupport::Dependencies.load_paths.first + c = ActiveSupport::Dependencies.ref("ServiceOne") + service_one_first = ServiceOne + assert_equal service_one_first, c.get + ActiveSupport::Dependencies.clear + assert ! defined?(ServiceOne) + + service_one_second = ServiceOne + assert_not_equal service_one_first, c.get + assert_equal service_one_second, c.get + end + end + def test_nested_load_error_isnt_rescued with_loading 'dependencies' do assert_raise(MissingSourceFile) do -- cgit v1.2.3