3

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)

mrzasa
  • 22,895
  • 11
  • 56
  • 94
user2012677
  • 5,465
  • 6
  • 51
  • 113

2 Answers2

3

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 :)
mrzasa
  • 22,895
  • 11
  • 56
  • 94
0

You should not need to concatenate or use parens on the method chain

def make_constant type
  "::#{type}".singularize.camelize.constantize
end
lacostenycoder
  • 10,623
  • 4
  • 31
  • 48