How to find controller methods defined for a controller in Rails 4? I look around in Rails.application
and find named routes defined but not the methods defined.

- 9,990
- 38
- 137
- 303
-
Maybe in the `controllers` folder where the controllers are defined? Or are you asking about `ActionController::Base`? – Jon Egeland Feb 25 '15 at 13:36
3 Answers
If you want to list all methods defined inside a specific controller (ie. UsersController
):
>> UsersController.instance_methods(false)
=> [:new, :create, :edit, :update, :update_remote, :user_params]
If you just want public
methods:
>> UsersController.public_instance_methods(false)
=> [:new, :create, :edit, :update, :update_remote]
If you need the whole list of methods, also the ones from ancestors, call those methods with true
(or without param, since it's the default):
UsersController.instance_methods
UsersController.public_instance_methods
More docs here: http://ruby-doc.org//core-2.2.0/Module.html#method-i-instance_methods
instance_methods
Returns an array containing the names of the public and protected instance methods in the receiver. For a module, these are the public and protected methods; for a class, they are the instance (not singleton) methods. If the optional parameter is false, the methods of any ancestors are not included.
public_instance_methods
Returns a list of the public instance methods defined. If the optional parameter is false, the methods of any ancestors are not included.
Alternatively, if you need to get the "local" methods, including the ones included from other modules, you can achieve it by:
u = UsersController.new
u.methods - u.class.superclass.instance_methods

- 6,709
- 1
- 38
- 48
-
The public_instance_methods lists out only the methods defined by the controller and does not include the methods included from other module. – user938363 Feb 25 '15 at 18:44
-
@user938363 I just updated answer with an alternative approach to list all methods (also the ones included by another module). – markets Feb 26 '15 at 10:19
TestClass.instance_methods(false)
to get only instance methods that belong to that class only.

- 1,072
- 2
- 11
- 22
method_defined?
seems to be straightforward to find out if a method is defined for a class. For example, QuotesController.method_defined?(:index)
returns true if there is index action in controller.
For an instance, it is obj_instance.methods.include?(:method_name)
Here is a post about method_defined? and methods.include?: Given a class, see if instance has method (Ruby).

- 1
- 1

- 9,990
- 38
- 137
- 303
-
1Yes, but this is not an answer to your OP, originally you asked for: "How to find controller methods defined for a controller in Rails 4?" So to find the methods you have to use `QuotesController.instance_methods(false)`. `method_defined?` is used to check for an existing method. – markets Feb 26 '15 at 09:59