mrEmpanada
mrEmpanada

Reputation: 35

Where should I put custom error classes when creating a new library?

I'm creating my first gem, and I'm struggling to find a place where I should place my custom error classes. That's how my gem is structured at the moment:

MyGem
|-lib
 /secrets
  - manager.rb
 secrets.rb

I added my custom error classes in the root file: secrets.rb. E.g:

module Secrets
  VERSION = "0.1.0"

  class DateError < StandardError; end
end

Because I'm new to Ruby and this is my first time creating a Gem, I'm not sure if there is a correct place to put those.

Upvotes: 1

Views: 118

Answers (1)

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84443

Two Common Approaches

There really isn't a hard rule about this. However, the two most sensible choices are:

  1. The primary library file for your gem (e.g. lib/secrets). That file is automatically loaded by the gem, and it seems like a reasonable place to put one-liners and boilerplate that apply to the whole gem.
  2. In a class file required from the primary library file for your gem (e.g. lib/secrets/date_error.rb). That's where most things that need to be required should live, and the consistent naming convention makes long-term maintenance easier.

Ruby being as flexible as it is, there's nothing stopping you from putting the code anywhere you like in your source tree. The core constraints are really namespacing (e.g. do you want the exception to be Secrets::DateError or something else?) and code maintenance, so putting the class inside an unrelated file like lib/secrets/versions.rb or lib/secrets/deeply/nested/path/date_error.rb) would seem to be less-than-ideal.

Upvotes: 2

Related Questions