Gemas con Un Gran Número de Utilidades Independientes

Some gems, however, may be made up of multiple parts that could be used independently of each other. ActiveSupport, for example, provides a large number of useful utilities that, while they function together, can also function separately.

If I add require active_support to my code I load all of ActiveSupport. While this may be what I want in some cases (like inside a Rails application) in other cases I may just want a specific piece of ActiveSupport. Luckily, ActiveSupport is designed to handle this well. If I, for instance, add require active_support/core_ext I will only be loading the Ruby core extensions that are a part of ActiveSupport.

How can you make this work in your library? It's quite simple: your base file should, when required, require all the other parts of your library. However, each part of your library should, at its top, require any other parts or external dependencies so that it may be included without the user having previously required the base file. Let's take a look at an example:

# in lib/my_gem.rb

require 'my_gem/widget'
require 'my_gem/widgets/foo_bar'
require 'my_gem/widgets/baz'

# in lib/my_gem/widget.rb

require 'external_library'

module MyGem
  class Widget
  end
end

# in lib/my_gem/widgets/foo_bar

require 'my_gem/widget'

module MyGem
  module Widgets
    class FooBar < MyGem::Widget
    end
  end
end
Each of the files in the above example can be required independently, giving developers the flexibility to use only a subset of your library's functionality if needed.

Remember that require statements will only load the code from a file once, so it is safe to require the same file multiple times.

Casiano Rodriguez León 2015-06-18