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,061
  • 1
  • 9
  • 23