DEV Community

Salman Sohail
Salman Sohail

Posted on • Originally published at salzam.com on

Creating a Ruby gem using Thor generator

I have been writing ruby gems for sometime now and always wish that there could be a command that can generate the gem structure/boilerplate and the things I love pre-configured for me.

This is where Thor comes in handy. I am going to introduce you to Thor a.k.a the badass command line generator that will make your life easy when it comes to ruby gem creation.

I do want to mention Mariella Miranda who’s article on this topic inspired me to create a project which can be used as a gem generator to save you a lot of time.

just imagine this command:

thor mygem age_calculator
Enter fullscreen mode Exit fullscreen mode

Produces this:

age_calculator
│ README.md
│ age_calculator.gemspec
│ Gemfile
│ .gitignore
│
└───lib
│ │ age_calculator.rb
│ └───age_calculator
        │ version.rb
│   
└───spec
    └───age_calculator
    │ age_calculator_spec.rb
    │ spec_helper.rb
Enter fullscreen mode Exit fullscreen mode

Let’s do this!

Install thor

gem install thor
Enter fullscreen mode Exit fullscreen mode

Clone my repository from github

git clone https://github.com/saluminati/gem_generator.git
Enter fullscreen mode Exit fullscreen mode

Link to my repo https://github.com/saluminati/gem_generator

Getting started

cd gem_generator
thor gem_generator age_calculator
Enter fullscreen mode Exit fullscreen mode

Your gem with all the required files is now created in the age_calculator directory

You can also append gem generator with use_rspec_suit and use_rubocop options have rspec and rubocop pre-installed and configured with your

Example:

thor gem_generator age_calculator --use_rspec_suit=true --use_rubocop=true
Enter fullscreen mode Exit fullscreen mode

Once your gem is created, make sure that you try to build it.

Example:

cd age_calculator
bundle install
gem build age_calculator.gemspec
Enter fullscreen mode Exit fullscreen mode

Some explanation – As I promised

Content of gem_generator.thor file

Our main file is gem_generator.thor which holds everything together.

This file is extended from Thor::Group which, in a nutshell will execute all the methods defined in this class in the order they were defined.

If you look at the methods inside this class, it is creating the gem directory and copying the templates files within your gem namespace with everything per-configured.

Happy coding! please let me know if you run into any issue.

Top comments (0)