Tip for object.methods in Ruby

21 June 2007 Whenever I want to take a quick peek at the methods an object supports in irb or script/console I do the trusty object.methods - unfortunately if you are working with Rails this produces a lot of output owing to the number of methods added by the framework (ever tried @controller.methods in a debugging session? it lists every single _path and _url route in your routes file).

So, to get something meaningful from your .methods output, try the following.

1
2
3
4
5
6
7
8
9
10
11
12
13
@controller.methods

>> [ lots of output ]

@controller.methods.sort (sorts the methods alphabetically)

>> [ lots of output in alphabetical order ]

@controller.methods.sort.grep(/action/)

>> ["action_name", "action_name=", "expire_action", "perform_action_with_benchmark", "perform_action_with_filters", 
"perform_action_without_benchmark", "perform_action_without_rescue", "render_action", "rendered_action_cache", 
"rendered_action_cache=", "rescue_action", "rescue_action_in_public", "rescue_action_locally"]

There we go, much better - I was able to just pick out the methods that matched what I was looking for and in alphabetical order. Magic

Comments

  1. Zach Inglis Says:
    I like to do something like: Model.methods.each do |method| p "#{method}
    " end

Sorry, comments are closed for this article.