When we run the bundle gem new_gem command, a directory is created with those files:
create new_gem/Gemfile
create new_gem/Rakefile
create new_gem/.gitignore
create new_gem/new_gem.gemspec
create new_gem/lib/new_gem.rb
create new_gem/lib/new_gem/version.rb
By default, the file new_gem/lib/new_gem.rb is a module named NewGem.
My question is the following: how can I do if NewGem is a class? Rather then having NewGem::NewGem, I would like to just define this class (without a root module).
I tried to just replace module by class inside this file, and then make a local gem in order to test it, but after its installation, I can not load it in IRB (with require 'new_gem').
Thanks for your help.
You should ask yourself why you want to do this. The module is there to namespace your gem’s code. Typically to provide a context for all the classes within, but even in a single class gem, this would help to provide conflicts with other code out in the world.
Unless your class is named
SomethingThatCouldNeverPossiblyBeDefinedAnywhereElse, leaving that module in place is probably a good thing. And regardless of that, leaving the module intact is still a good thing as it’s the convention, and what people expect when examining/using your code.With that in mind, there are a few things you’d need to do if you wanted a single class gem.
The generated gemspec wants to
require 'new_gem/version'to find it’s version number. Change that to simplyrequire 'new_gem'.The gemspec also lists its contained files using
git ls, and the generated gem package already hasnew_gem/versionincluded in the pre-built git repo. Remove this:Change your
new_gemmodule to a class, as you did previously.Remove the generated
version.rbrequire from your class, and instead define the version there, e.g.:Finally install the gem via
rake install. You won’t be able to load it in IRB until you’ve done this.