Skip to content

Commit 766a0cd

Browse files
robin850rafaelfranca
authored andcommitted
Avoid relying on error messages when rescuing
When we are rescuing from an error, it's a brittle approach to do checks with regular expressions on the raised message because it may change in in the future and error messages are different across implementations. The NameError API could be improved at the MRI level but for now we need to rely on its #name. A #== check will only pass for top level constants or only when the last constant of the path is missing so we need to rely on #include? instead. For instance: begin Namespace::Foo rescue NameError => e e.name # => :Namespace end However, if the name-space already exists, only the name of the first missing constant in the path is returned (e.g. for Math::PHI, the name would be :PHI). JRuby will return a fully qualified name (:"Math::PHI"). We need to keep the == check for 1.9 compatibility since const_get will raise a NameError with a name attribute set to the given string if it's one of "::" or "". See http://git.io/jnSN7g for further information.
1 parent 7fd06ee commit 766a0cd

File tree

1 file changed

+2
-2
lines changed
  • activesupport/lib/active_support/inflector

1 file changed

+2
-2
lines changed

activesupport/lib/active_support/inflector/methods.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -280,8 +280,8 @@ def constantize(camel_cased_word)
280280
def safe_constantize(camel_cased_word)
281281
constantize(camel_cased_word)
282282
rescue NameError => e
283-
raise unless e.message =~ /(uninitialized constant|wrong constant name) #{const_regexp(camel_cased_word)}$/ ||
284-
e.name.to_s == camel_cased_word.to_s
283+
raise if e.name && !(camel_cased_word.to_s.split("::").include?(e.name.to_s) ||
284+
e.name.to_s == camel_cased_word.to_s)
285285
rescue ArgumentError => e
286286
raise unless e.message =~ /not missing constant #{const_regexp(camel_cased_word)}\!$/
287287
end

0 commit comments

Comments
 (0)