Skip to content

Latest commit

 

History

History
23 lines (18 loc) · 536 Bytes

001-safe-constantize.md

File metadata and controls

23 lines (18 loc) · 536 Bytes

About #safe_constantize

The String#constantize method converts a string to the constant (class, module) that the string contains or throws a NameError if there is no such constant.

def category
  category_class.new(self)
end

def category_class
  "Category::#{target_type}".constantize
rescue
  Category::Default
end

Fortunately, there is #safe_constantize which returns nil if there is no such constant:

def category_class
  "Category::#{target_type}".safe_constantize || Category::Default
end