0

I have a function that returns a User or nil if it can't find the user. It looks like this:

  # Given an access token in the HTTP headers, it returns the User who owns the token
  #
  # @return [User] the user who owns the access token
  def set_api_user
    token = /(.*)=\"(.*)\"/.match(request.headers["Authorization"])[2]
    @api_user = ApiKey.find_by(access_token: token).user
  end

My question is, how do I document that it returns a User or nil if it can't find it?

Hommer Smith
  • 26,772
  • 56
  • 167
  • 296
  • If find by returns and empty object won't this fail with the .user afterwards? Perhaps you should add a: @api_user = ApiKey.find_by(access_token: token).user rescue nil This way it's autodocumented and safer. – Jorge de los Santos Jun 04 '14 at 21:21

1 Answers1

1

Ignoring the behaviour of the code for error conditions etc, in Yard, you just add the alternatives into the comment:

# @return [User,nil] the user who owns the access token

The Yard renderer will do something like this with it:


  • (User?) set_api_user

    the user who owns the access token


The little question mark is Yard's convention for "maybe you'll get this, or maybe you'll get nil"

Neil Slater
  • 26,512
  • 6
  • 76
  • 94