0

I have the following statement which does work although it uses eval:

  def resource_name
    self.class.to_s.match(/(.+)Controller/)[1].singularize
  end

  def collection
    @collection ||= eval "#{resource_name}.all(sort: [[:name, :asc]])"
  end

Is there a better way of doing this that does not use eval?

2 Answers 2

4

Use Object#send instead, after you constantize the resource name: http://ruby-doc.org/core-1.9.3/Object.html#method-i-send

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

1 Comment

better use public_send instead of send, it prevents you from calling private methods like system
2

If I understand correctly you're trying to go from the string 'Product' to the constant Product, so you could just use

Object.const_get(resource_name)

If you're using Rails, you can also use constantize which has the advantage of understanding things like Module::SomeClass

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.