Try creating a gem based on bundler's official guide on developing a Ruby gem.
Running bundle gem foodie
will create a structure and generate files in the lib
directory:
- foodie
- version.rb
- foodie.rb
foodie.rb reads
require "foodie/version"
module Foodie
# Your code goes here...
end
Running ruby lib/foodie.rb
(or also from different directories) will result in
C:/Ruby23-x64/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require': cannot load such file -- foodie/versio
n (LoadError)
from C:/Ruby23-x64/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from foodie.rb:1:in `<main>'
On the other hand installing the gem via rake install
and then requiring the gem works just fine.
It works from source if require "foodie/version"
is changed to require_relative "foodie/version"
in foodie.rb. As I understand
require
works based on modulesrequire_relative
works based on directory structure
To me the latter looks like a hack. It'd no longer make sense to structure your code via modules as it wouldn't be enforced (maybe it'd still make sense but you could make mistakes and never notice).
My questions are:
- Is it possible to test a gem from source without installing it while following the bundler convention (using
require
instead ofrequire_relative
)? - Why does the gem work after installed?
- Is there any best practice for the usage of
require
,require_relative
, modules, files and general structure?
Thank you.