Reputation: 223
I have this code...
foo = opt_source.downcase.camelize
"#{foo}".new.start_check
this should call a class and the method start_check, but I am getting an undefined method error
undefined method `start_check' for "Abcd":String (Abcd is the class that foo represents)
Any suggestions on how what I am doing wrong?
Upvotes: 1
Views: 2225
Reputation: 513
Create a class name from a plural table name like Rails does for table names to models.
http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-classify
camelize is not fit to convert plural string into active record class if you are calling method from active record
For example:
u = "batteries"
u.camelize #=> "Batteries"
u.classify #=> ""Battery"
Try
opt_source.classify.constantize.new.send(:start_check)
Upvotes: 0
Reputation: 7127
You need to convert that string into a constant. Historically this was done with eval
but this leads to security issues in your code -- never eval
user-supplied strings.
The correct way to do this (in Rails) is via String#constantize:
foo = opt_source.downcase.camelize
foo.constantize.new.start_check
For ruby, use Kernel#const_get:
foo = opt_source.downcase.camelize
Kernel.const_get(foo).new.start_check
Don't forget to check for errors before calling your methods.
Upvotes: 4