user1563849
user1563849

Reputation: 223

undefined method error for :string

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

Answers (3)

Manivannan Jeganathan
Manivannan Jeganathan

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

Jeff Paquette
Jeff Paquette

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

Yevgeniy Anfilofyev
Yevgeniy Anfilofyev

Reputation: 4847

Just eval(foo).new.start_check

Upvotes: 0

Related Questions