0

I am trying to add variable name into method_name in rails. I am getting error.

**Controller ACTION**
=====================
def my_action(state)
   method_#{state}
end

**Model methods**
====================
def method_start
end

def method_end
end

how to call method with variable name i am not getting.

3
  • 2
    possible duplicate of How to call methods dynamically based on their name? Commented Sep 15, 2015 at 7:27
  • here i need to call different model methods. is it possible using this method? Commented Sep 15, 2015 at 7:35
  • Class_eval is typical pattern for meta-programming Commented Sep 15, 2015 at 8:38

1 Answer 1

2

Use Object.send to call method by name. For example,

def my_action(state)
  if [:start, :end].include?(state)
    model.send("method_#{state}")
  end
end

Make sure to validate state variable for security. Object.send can call any method including private ones.

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

1 Comment

Whenever possible, it's better to use public_send when calling from outside the class. public_send can only call public methods, not private ones. Calling a private method from outside the containing class breaks encapsulation and should be avoided.

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.