aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/lib/active_support/inflector/methods.rb
diff options
context:
space:
mode:
authorJosé Valim <jose.valim@gmail.com>2011-09-23 16:16:53 +0200
committerJosé Valim <jose.valim@gmail.com>2011-09-23 16:21:49 +0200
commitb2f34d1e3591df0f19f01ba30160661175c9a6b6 (patch)
treee74fed35ee03c122fee3399a19db00a2bd711b51 /activesupport/lib/active_support/inflector/methods.rb
parent310565f537b5eeb134e9a4bb0801358432f03e04 (diff)
downloadrails-b2f34d1e3591df0f19f01ba30160661175c9a6b6.tar.gz
rails-b2f34d1e3591df0f19f01ba30160661175c9a6b6.tar.bz2
rails-b2f34d1e3591df0f19f01ba30160661175c9a6b6.zip
Ensure that constantize just rescues NameError that applies to the constant being currently loaded.
Diffstat (limited to 'activesupport/lib/active_support/inflector/methods.rb')
-rw-r--r--activesupport/lib/active_support/inflector/methods.rb24
1 files changed, 20 insertions, 4 deletions
diff --git a/activesupport/lib/active_support/inflector/methods.rb b/activesupport/lib/active_support/inflector/methods.rb
index b22e39c7c2..dd232a5e2f 100644
--- a/activesupport/lib/active_support/inflector/methods.rb
+++ b/activesupport/lib/active_support/inflector/methods.rb
@@ -245,12 +245,15 @@ module ActiveSupport
# "blargle".safe_constantize # => nil
def safe_constantize(camel_cased_word)
begin
- camel_cased_word.constantize
- rescue NameError
- nil
+ constantize(camel_cased_word)
+ rescue NameError => e
+ raise unless e.message =~ /uninitialized constant #{const_regexp(camel_cased_word)}$/ ||
+ e.name.to_s == camel_cased_word.to_s
+ rescue ArgumentError => e
+ raise unless e.message =~ /not missing constant #{const_regexp(camel_cased_word)}\!$/
end
end
-
+
# Turns a number into an ordinal string used to denote the position in an
# ordered sequence such as 1st, 2nd, 3rd, 4th.
#
@@ -273,5 +276,18 @@ module ActiveSupport
end
end
end
+
+ private
+
+ # Mount a regular expression that will match part by part of the constant.
+ # For instance, Foo::Bar::Baz will generate Foo(::Bar(::Baz)?)?
+ def const_regexp(camel_cased_word) #:nodoc:
+ parts = camel_cased_word.split("::")
+ last = parts.pop
+
+ parts.reverse.inject(last) do |acc, part|
+ part.empty? ? acc : "#{part}(::#{acc})?"
+ end
+ end
end
end