is there any way to embed a comment in a Ruby method that could be outputted via irb or rails c

StackOverflow https://stackoverflow.com/questions/19410675

  •  01-07-2022
  •  | 
  •  

Question

Is there a way to do something like this:

>Location.get_info 
......
>Location.get_info --help
outputs info on the location; lazily loads hours 

where the output is embedded as maybe an rdoc style comment? I am looking to be able to have quick documentation for a set of seed commands for our rails app

thx

Was it helpful?

Solution

you can build nearly everything in ruby...

i don't think that there is any library out there doing what you want.

guessing from the IRB tag that you put on your post, you want to help people using your code.

in that case you could tell them to use pry and use the show-doc functionality

[2] pry(main)> show-doc User#url

From: /Users/paule/Documents/rails/on_ruby/app/models/user.rb @ line 39:
Owner: User
Visibility: public
Signature: url()
Number of lines: 1

generates a homepage url for a user

OTHER TIPS

Methods aren't objects, therefore you cannot store anything in them.

You can obtain a proxy object for a bound method using the Object#method method and for an unbound method using the Module#instance_method method, but that proxy object is, well, just a proxy object. In particular, it is not guaranteed that you will always get the same proxy object when you ask for one.

So, if you obtain a proxy object for a method, then store some documentation in it, then later obtain another proxy object for the same method, this might be a different proxy object which doesn't have your documentation in it.

Example:

class UnboundMethod
  attr_accessor :doc
end

map = Array.instance_method(:map)

map.doc = '`map` maps a block over all elements'

map_again = Array.instance_method(:map)

map_again.doc
# => nil

map.doc
# => '`map` maps a block over all elements'

map.object_id == map_again.object_id
# => false

So, you cannot store your documentation in the method, because methods aren't objects and you cannot store it in the proxy object, because Ruby doesn't guarantee the identity of those proxy objects.

You need to store it somewhere else. Maybe in the Module the method is defined in, indexed by the method name.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top