Documenting Ruby Code With Friendly Usage Examples
Ruby has a really cool feature where you can add code that only runs when it's enclosing file is run directly (as opposed to being run from a different code or test file that requires it). All you need to do is wrap the optional code in the following block:
if__FILE__==$0 # Your optional code here end
I like to use this as an opportunity to add usage examples to demonstrate the functionality of the main code. For example, the main code in my "project.rb" class file is:
class Project attr_reader :name, :purpose, :dependencies def initialize(name = "Project", purpose = "No purpose") @name = name @purpose = purpose @dependencies =  end def add_dependency(dependency) @dependencies << dependency end def remove_dependency(dependency) @dependencies.delete(dependency) end end
While it's fairly easy to figure out what's going on with this class, it's a little more difficult to imagine it working in the context of a real-world program. The usage examples at the bottom of the file bring it to life, which makes it easier to understand why you might want to use it, and how it can be adapted to your own purposes.
# Run usage examples only when current file is run directly if __FILE__==$0 # ----- Example Data ----- name = "Knit a bear" purpose = "Birthday gift" dependencies = ["Knitting Pattern", "Yarn", "Pizza"] # ----- Usage Examples ----- # ✨ Create new project with a name and purpose bear_project = Project.new(name, purpose) dependencies.each do |dependency| # ✨ Add a project dependency bear_project.add_dependency(dependency) end # ✨ Remove project dependencies bear_project.remove_dependency("Pizza") # ----- Expected Output ----- puts bear_project.name # => Knit a bear puts bear_project.purpose # => Birthday Gift puts bear_project.dependencies # Knitting Pattern\nYarn end
When you run the project.rb file directly (
ruby project.rb), you should get the following output:
Knit a bear Birthday Gift Knitting Pattern Yarn
When you run a file that requires and uses the project.rb file (e.g.
ruby project_spec.rb or
ruby roadmap.rb. Then the usage examples won't run and you won't see the above output in the console.