Reputation: 1147
How do I document a function that returns a value, while a null return value should raise a warning?
So currently the method below would be valid because yard allows for the specified type or void.
# @return [String]
def say_hello
nil
end
Upvotes: 2
Views: 2095
Reputation: 84413
In YARD, the documentation provides a clear example of how to define multiple return types in the Declaring Types section. The same section says you're allowed to use the void
meta-type to mean "no meaningful value," but since Ruby doesn't really have void methods I think that using nil
as an expected return type (rather than void
) is generally more semantically useful.
So, to document a return type of either String
or void
, you could express it thus:
# @return [String, void]
def say_hello
nil
end
YARD is for documentation, and doesn't actually enforce the types found in method signatures or contracts of any kind. So, your question seems like an X/Y problem because it's still up to the method or the caller to raise warnings or trigger an exception.
A better way to express what you seem to want is to use Kernel#warn or Kernel#raise to address your expections. For example, consider:
# @param string [String]
# @raise [ArgumentError] argument missing or not String
# @return [String]
def say_hello string
unless string.is_a? String
raise ArgumentError, "string: #{string.class}, not String"
end
string
end
Ruby is a duck-typed language. Even though my example above seems like an improvement, it may still ultimately be a work-around for doing something non-Rubyish within your code. Without seeing your real code, this seems like a more reasonable way to enforce a contract between this method and an unknown caller. Of course, your mileage may certainly vary.
Upvotes: 7