From 310565f537b5eeb134e9a4bb0801358432f03e04 Mon Sep 17 00:00:00 2001 From: Ryan Oblak Date: Thu, 22 Sep 2011 12:17:42 -0700 Subject: Added ActiveSupport::Inflector.safe_constantize and String#safe_constantize; refactored common constantize tests into ConstantizeTestCases --- .../lib/active_support/inflector/methods.rb | 27 ++++++++++++++++++++++ 1 file changed, 27 insertions(+) (limited to 'activesupport/lib/active_support/inflector') diff --git a/activesupport/lib/active_support/inflector/methods.rb b/activesupport/lib/active_support/inflector/methods.rb index 423b5abd20..b22e39c7c2 100644 --- a/activesupport/lib/active_support/inflector/methods.rb +++ b/activesupport/lib/active_support/inflector/methods.rb @@ -224,6 +224,33 @@ module ActiveSupport end end + # Tries to find a constant with the name specified in the argument string: + # + # "Module".safe_constantize # => Module + # "Test::Unit".safe_constantize # => Test::Unit + # + # The name is assumed to be the one of a top-level constant, no matter whether + # it starts with "::" or not. No lexical context is taken into account: + # + # C = 'outside' + # module M + # C = 'inside' + # C # => 'inside' + # "C".safe_constantize # => 'outside', same as ::C + # end + # + # nil is returned when the name is not in CamelCase or the constant is + # unknown. + # + # "blargle".safe_constantize # => nil + def safe_constantize(camel_cased_word) + begin + camel_cased_word.constantize + rescue NameError + nil + end + end + # Turns a number into an ordinal string used to denote the position in an # ordered sequence such as 1st, 2nd, 3rd, 4th. # -- cgit v1.2.3