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.

1 Answers1

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.

Shouichi
  • 1,090
  • 1
  • 10
  • 25
  • 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. – Steven Hirlston Nov 29 '22 at 01:52