def xxx(class)
cl = "#{class}".safe_constantize
return '' unless cl
cl.name
end
my spec
context 'class exist' do
it 'return instance of ' do
xxx("String").should be_eql "String"
end
end
context 'class does not exist' do
it 'return empty string' do
xxx("foo").should be_eql ''
end
end
Then when run my test first(class exist) pass but second fail surprisingly with exeption
Failure/Error: xxx
NameError:
uninitialized constant foo
thats is wierd because documentation says:
# +safe_constantize+ tries to find a declared constant with the name specified
# in the string. It returns nil when the name is not in CamelCase
# or is not initialized. See ActiveSupport::Inflector.safe_constantize
#
# 'Module'.safe_constantize # => Module
# 'Class'.safe_constantize # => Class
# 'blargle'.safe_constantize # => nil
activesupport (4.1.7)
rspec (2.13.0)
rails (4.1.7)
ruby (2.1.2)
I suppose save_constantize is raising exection insted of return nil.