1

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?

1
  • what's the value of opt_source? I need to know on which you called new. Commented Apr 8, 2013 at 14:55

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Just eval(foo).new.start_check

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.