Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 419
user2012677 Avatar asked May 16 '26 03:05

user2012677


1 Answers

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 :)
like image 154
mrzasa Avatar answered May 18 '26 18:05

mrzasa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!