Yard doc and `define_method`
Asked Answered
S

1

11

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.

Sneeze answered 9/2, 2015 at 15:19 Comment(3)
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?Paradiddle
Nothing appears : no methods and no docs for these methodsSneeze
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.Paradiddle
A
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

Abelmosk answered 9/2, 2015 at 17:40 Comment(3)
why doesn't it work in a loop? [:one,:two,:three].each {|n| generate(n)}. does it?Subject
OK @Abelmosk 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?Subject
@Subject I guess this is the way YARD works. Besides, I think method definition inside a loop is less readable, but YMMV.Abelmosk

© 2022 - 2024 — McMap. All rights reserved.