Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Check if Controller Index Exists

Is there a way to check if there exists an index action for a controller? Something like:

Controller.indexActionExists?

I have seen posts to check if specific routes exist, but those methods aren't working for me, since some of my index actions aren't associated with routes.

like image 600
Ester Lin Avatar asked Mar 15 '23 02:03

Ester Lin


1 Answers

The action_methods method is going to be the most expedient tool in this case, returning a Set of method names. Give the following code a shot:

# Get a set of method names belonging to a controller called 'MyController'

methods = MyController.action_methods

if methods.include? "index"
  puts "MyController has an index method"
else
  puts "MyController lacks an index method"
end
like image 187
MarsAtomic Avatar answered Mar 23 '23 05:03

MarsAtomic