stevec
stevec

Reputation: 52967

How to get documentation for a method in a Ruby gem?

I'm trying to find out about the can? method used by cancancan gem.

I tried here, but cannot locate the method can?:

enter image description here

As suggested here, I tried these:

can?.arity
NoMethodError: undefined method `can?' for main:Object

can?.parameters
NoMethodError: undefined method `can?' for main:Object

I'm simply trying to find out what parameters can? (the cancancan method used in the view) wants to receive, but this example is a good opportunity to learn how to do this for other methods as well, hence I hope for a general solution (one that will allow me to look up documentation for methods beyond the one asked in this specific example).

Thanks in advance for all help/pointers!

Upvotes: 10

Views: 1589

Answers (4)

Chris Heald
Chris Heald

Reputation: 62698

As an alternative to using external sites, you can try ri from the command line:

ri "can?"

When you install a gem, the ri documentation is (usually) installed as well. The ri command line tool will search installed gem documentation for methods and constants matching your input and present them.

Since it runs locally, this can be a great resource when you don't have an internet connection handy!

enter image description here

Upvotes: 6

max pleaner
max pleaner

Reputation: 26788

Jörg's answer is correct, but I also wanted to show some alternate ways to find the source code for a method:

  1. Use show-source from Pry gem:

    show-source CanCan::Ability#can?
    

    of course, to do this you would need to know that the method is defined on CanCan::Ability. To find that information out you could use <my_record>.method(:own?).owner.

  2. Use source-location in Ruby core:

    You can use <record>.method(:own?).source_location - this will tell you the file that the method is defined in as well as the line number, so you can open it up in text editor to inspect

Upvotes: 2

stevec
stevec

Reputation: 52967

Not an answer, but just some tips I was told in another forum:

  • Not every ruby gem method will be have documentation for every method, so don't expect to find documentation for every method for every gem
  • Try finding the source code (e.g. github), and searching the particular repository for the method name with def prepended all in double quotes. That is:

Go to the github repository, then go to the search bar (top left), then search like so (and select "In this repository" when searching)

enter image description here

That will give these search results:

enter image description here

And we can see the method defined here:

enter image description here

Upvotes: 4

J&#246;rg W Mittag
J&#246;rg W Mittag

Reputation: 369614

The easiest way is to enter can? into the search bar of the site you linked, which gives these two results:

Upvotes: 4

Related Questions