Search code examples
rubydocumentationyard

Yard doc and `define_method`


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.


Solution

  • 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