0
votes

I'm working on a ruby gem which can generate some code in other language. The gem needs to load the models in the current rails app. And it's implemented as a generator which accepts one parameter -- the table name. Inside it, read the columns definition from that table in this way:

tableklass = table_name.to_s.constantize  # get the class name from table_name
cols = tableklazz.columns  # get columns definitions.

When I run the generator 'rails g mygen Product'. It always gave me the error below:

.../ruby/gems/2.3.0/gems/activesupport-4.2.4/lib/active_support/inflector/methods.rb:261:in `const_get': wrong constant name products (NameError)

How can I fix this error? Or whether is there other better way to do so (read table information to generate some code)?

1

1 Answers

2
votes

constantize expects camelized input. I am not sure, what is happening inside your generator, but it looks like constantize finally receives products as a parameter. Safest version of what you are trying to do:

table_name.to_s.singularize.camelize.constantize

Everything below would work:

:products.to_s.singularize.camelize.constantize
:product.to_s.singularize.camelize.constantize
'product'.to_s.singularize.camelize.constantize
Product.to_s.singularize.camelize.constantize