From 0536ea8c7855222111fad6df71d0d09b77ea4317 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Wed, 23 Nov 2011 21:43:03 +0000 Subject: Add safe_constantize to ActiveSupport::Dependencies. --- activesupport/lib/active_support/dependencies.rb | 33 ++++++++++++++---------- 1 file changed, 20 insertions(+), 13 deletions(-) (limited to 'activesupport/lib') diff --git a/activesupport/lib/active_support/dependencies.rb b/activesupport/lib/active_support/dependencies.rb index db90de4682..2f1066016b 100644 --- a/activesupport/lib/active_support/dependencies.rb +++ b/activesupport/lib/active_support/dependencies.rb @@ -527,7 +527,7 @@ module ActiveSupport #:nodoc: class ClassCache def initialize - @store = Hash.new { |h, k| h[k] = Inflector.constantize(k) } + @store = Hash.new end def empty? @@ -538,23 +538,23 @@ module ActiveSupport #:nodoc: @store.key?(key) end - def []=(key, value) - return unless key.respond_to?(:name) - - raise(ArgumentError, 'anonymous classes cannot be cached') if key.name.blank? - - @store[key.name] = value + def get(key) + key = key.name if key.respond_to?(:name) + @store[key] ||= Inflector.constantize(key) end - def [](key) + def safe_get(key) key = key.name if key.respond_to?(:name) - - @store[key] + @store[key] || begin + klass = Inflector.safe_constantize(key) + @store[key] = klass + end end - alias :get :[] - def store(name) - self[name] = name + def store(klass) + return self unless klass.respond_to?(:name) + raise(ArgumentError, 'anonymous classes cannot be cached') if klass.name.empty? + @store[klass.name] = klass self end @@ -571,10 +571,17 @@ module ActiveSupport #:nodoc: end # Get the reference for class named +name+. + # Raises an exception if referenced class does not exist. def constantize(name) Reference.get(name) end + # Get the reference for class named +name+ if one exists. + # Otherwise returns nil. + def safe_constantize(name) + Reference.safe_get(name) + end + # Determine if the given constant has been automatically loaded. def autoloaded?(desc) # No name => anonymous module. -- cgit v1.2.3