10

Is there a way to comment methods defined with define_method in YardDoc?

I tried this:

%w(one two three).each do |type|
  # The #{type} way
  # @return [String] the #{type} way
  define_method("#{type}_way") do ... end
end

But, unfortunately, not working.

sawa
  • 165,429
  • 45
  • 277
  • 381
JoJoS
  • 1,971
  • 2
  • 13
  • 15
  • Describe what "not working" means. You get no output? You get output but it's not formatted? It's formatted but it's not the format you want? – the Tin Man Feb 09 '15 at 15:37
  • Nothing appears : no methods and no docs for these methods – JoJoS Feb 09 '15 at 15:58
  • You can't document a dynamically created method, it has to be statically defined. Yard would have to run your code then use introspection to generate the methods available at run time, which is not practical. – the Tin Man Feb 09 '15 at 16:09

1 Answers1

11

If you move the method creation into a class method, you could use a macro:

class Foo

  # @!macro [attach] generate
  #   @method $1_way
  #   The $1 way
  #   @return [String] the $1 way
  def self.generate(type)
    define_method("#{type}_way") do
    end
  end

  generate :one
  generate :two
  generate :three

end

YARD Output:

- (String) one_way

The one way

Returns:

(String) — the one way


- (String) three_way

The three way

Returns:

(String) — the three way


- (String) two_way

The two way

Returns:

(String) — the two way

Stefan
  • 109,145
  • 14
  • 143
  • 218
  • why doesn't it work in a loop? `[:one,:two,:three].each {|n| generate(n)}`. does it? – masciugo Feb 12 '15 at 14:43
  • OK @Stefan but.. in cases like this, do we really have to adapt code in order to use YARD? I mean maybe less readable code in favor of auto doc production ... or is there some other way to document methods that are dynamically defined? – masciugo Feb 13 '15 at 10:14
  • @masciugo I guess this is the way YARD works. Besides, I think method definition inside a loop is less readable, but YMMV. – Stefan Feb 13 '15 at 10:22