Zag zag..
Zag zag..

Reputation: 6231

New gem with Bundler, from a class

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.

Upvotes: 1

Views: 470

Answers (1)

numbers1311407
numbers1311407

Reputation: 34072

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.

  1. The generated gemspec wants to require 'new_gem/version' to find it's version number. Change that to simply require 'new_gem'.

  2. The gemspec also lists its contained files using git ls, and the generated gem package already has new_gem/version included in the pre-built git repo. Remove this:

    git rm lib/new_gem/version.rb
    
  3. Change your new_gem module to a class, as you did previously.

  4. Remove the generated version.rb require from your class, and instead define the version there, e.g.:

    class NewGem
      VERSION = '0.0.1'
    end 
    
  5. Finally install the gem via rake install. You won't be able to load it in IRB until you've done this.

Upvotes: 3

Related Questions