Skip to content

Instantly share code, notes, and snippets.

@ms-ati
Last active March 15, 2021 11:09
Show Gist options
  • Save ms-ati/605bc77213cbff978e53 to your computer and use it in GitHub Desktop.
Save ms-ati/605bc77213cbff978e53 to your computer and use it in GitHub Desktop.
Example: document a Value class with YARD
##
# Examples of trying document classes created with Values gem,
# using YARD.
# https://github.com/tcrayford/Values
##
# Works 100%: Assigning a new Struct class to a constant
# And you can document the fields using `@attr`.
#
# @attr [Array<String>] a names of stuff
# @attr [Set<Fixnum>] b numbers of stuff
Example1 = Struct.new(:a, :b)
# Doesn't work: Assigning a new Value class to a constant
#
# @attr_reader [Array<String>] a names of stuff
# @attr_reader [Set<Fixnum>] b numbers of stuff
Example2 = Value.new(:a, :b)
# Works 75%: Inheriting from a new Value class
# You can document the fields using `@attr_reader`, but if you don't do that,
# then they won't appear at all.
#
# Also, this generates the Yard warning 'Undocumentable superclass'.
#
# @attr_reader [Array<String>] a names of stuff
# @attr_reader [Set<Fixnum>] b numbers of stuff
class Example3 < Value.new(:a, :b); end
# Doesn't work: Inheriting from a new Value class, doc with `@attribute [r]`
#
# Despite the YARD docs telling us that `@attr_reader` is deprecated in
# favor of `@!attribute`, the latter appears to not be supported in Rubymine,
# so it's not viable.
#
# @!attribute [r] a
# @return [Array<String>] names of stuff
# @!attribute [r] b
# @return [Set<Fixnum>] numbers of stuff
class Example4 < Value.new(:a, :b); end
v1 = Example3.new([], [])
# Rubymine correctly completes, offering methods of String
#v1.a.first.
v2 = Example4.new([], [])
# Rubymine fails to complete, must not work with !@attribute yet
#v2.a.first.
###
### Proposal
###
# What is a person?
#
# @attr_reader [String] name Full name
# @attr_reader [Fixnum] age Age in years
# @attr_reader [Array<Person>] friends List of friends
class Person < Value.new(:name, :age, :friends); end
alice = Person.new('Alice', 23, [])
bobby = Person.new('Bobby', 34, [alice])
# Rubymine correctly completes, offering methods of Person
#bobby.friends.first.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment