constantizeした時にactive_support/inflector/methods.rb:268:in `const_get': uninitialized constant Hoge (NameError)と怒られる問題[Rails]

h = 'Hoge'.constantize
h.create(fuga: 'fuga')

した時に

active_support/inflector/methods.rb:268:in `const_get': uninitialized constant Hoge (NameError)

Hogeという定数、クラスがなかったため怒られてしまった。

safe_constantizeで回避

safe_constantizeを使うと存在しなかった場合 nil が返されます nilチェックしてから実行して回避

h = 'Hoge'.safe_constantize
h.create(fuga: 'fuga') unless h.nil?