Okiba Okiba - 6 months ago 12
Ruby Question

Convert symbol into an object

My method takes an argument. I prefer to avoid directly passing the object like so:

def print_error(Loggers::MyLogger.new, error)
...
end


Instead, I would like to pass a symbol like so:

def print_error(:my_logger, error)
...
end


Is there an elegant way to convert
:my_logger
symbol into a
MyLogger
instance? Or do I have to build a factory mechanism for that?

Answer

In Rails there is a helper ready for that constantize:

:my_logger.to_s.constantize
#⇒ MyLogger

In Ruby one might do it using Module#const_get:

klazz = :my_logger.to_s.gsub(/(\A|_)(.)/) { |m| m[-1].upcase }
const_get(klazz) if const_defined?(klazz)
#⇒ MyLogger