archSeer/ruby-mpd — pull request #22 by mikerodrigues (2014-12-20 05:22:31+00:00)
Title: use require_relative for more flexibility when loading the gem

Without this commit, the gem can't be used without being installed in RubyGems or otherwise added to the load path:

$ git clone https://github.com/archSeer/ruby-mpd.git
$ cd ruby-mpd
$ pry

[1] pry(main)> require_relative './lib/ruby-mpd'
LoadError: cannot load such file -- ruby-mpd/version
from /home/michael/.rvm/rubies/ruby-2.0.0-p353/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require'

Using `require 'ruby-mpd/version'` within `./lib/ruby-mpd.rb` means that we will load the RubyGems version of that file rather than the `./lib/ruby-mpd/version`, even though within pry we are loading the relative path `./lib/ruby-mpd` and not the version installed in RubyGems.

Using `require_relative` means I can easily load a modified gem from a local git branch, or form RubyGems without otherwise messing with the load path, and without having to worry about a mix of files be loaded from the git repo and some being loaded from RubyGems:

`require 'ruby-mpd'` - loads from RubyGems

`require './lib/ruby-mpd'` or `require_relative './lib/ruby-mpd'` loads from the relative path in the git repo.

You also get the benefit of a simplified gemspec.

https://practicingruby.com/articles/ways-to-load-code