Dowemo
0 0 0 0


Question:

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.


Best Answer:


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



Copyright © 2011 Dowemo All rights reserved.    Creative Commons   AboutUs