Search code examples
rubyyardyardoc

YARD for keyword arguments with default hash


I have a method that looks like this:

def get_endpoint(params: {})
end

I want the caller of this method to be able to pass in a few optional parameters.

I want to write YARD documentation to support this and if I wasn't using keyword arguments I'd use the @option declaration.

However, YARD's own docs say:

Note: For keyword parameters, use @param, not @option.

So I tried:

  # @param params [Hash] options to be used in request
  # @param date [String] date in YYYYMMDD
  # @param start_time [Integer] start_time in Epoch

That fails because YARD only sees the params keyword argument I'm using. The exact failure is:

@param tag has unknown parameter name: date

So then I tried to use the @option syntax replaced with the param keyword:

  # @param params [Hash] options to be used in request
  # @param params [String] :date in YYYYMMDD
  # @param params [Integer] :start_time in Epoch

That results in a different error:

@param tag has duplicate parameter name: params

Ideally I want to describe the params hash with the 3 or 4 options the user of this method can use. Is there a way to do this?


Solution

  • That signature does not use keyword arguments for :date or :start_time. Keyword arguments for those arguments would be specified as something like:

    def get_endpoint(date:, start_time:)
    

    @option is specifically meant for specifying options that would be contained within an options Hash in your case params. Since you are using a keyword argument for params I would recommend adding the @param tag for this as well to clearly identify the keyword argument. For Example:

    @param params [Hash]  options to be used in request
    @option params [String] :date in YYYYMMDD
    @option params [Integer] :start_time in Epoch
    

    Documentation for @options just in case.