Search code examples
ruby-on-railsrubymetaprogrammingruby-on-rails-5.2

Dynamically create an escaped constant (Ruby on Rails)


I need to dynamically create a constant that is escaped out of the current namespace, so I need the '::' in front of my constant. However, when I try the below, I get the below error...

def make_constant(type)     
  "::"+"#{type}".singularize.camelize.constantize
end

When I try some thing like

make_constant("MyModel") the result should be a constant of:

::MyModel

However, I get and error:

TypeError (no implicit conversion of Class into String)


Solution

  • In Ruby + has lower priority than method invocation ., so you first create a class with "#{type}".singularize.camelize.constantize and then you try to add this class to a string '::' that fails.

    To fix it you can:

    ("::"+"#{type}".singularize.camelize).constantize # ugly, but proves the point
    "::#{type.singularize.camelize}".constantize #elegant and working :)