Creating the SeaLife CLI Gem

Posted by Matt Etress on October 16, 2018

Going into my CLI Gem Portfolio Project, I wasn’t sure what I wanted to make. This called for some serious brainstorming. 💡Got it! I’ll make a gem that provides information about sea creatures. Everyone loves sea creatures!

The first task I set out to do was to decide how I wanted the application to work. So, I sat down with a pencil and paper (I know, what are those?) and began with a simple outline. First, I wanted the CLI to welcome the user and provide a list of categories that the user could choose from. From there the user just needs to type in the number of a category, and they’ll be given a list of animals that belong to that category. The user can once again enter the number of his/her selection and will be presented with information about the animal including its scientific name, habitat, feeding habits, and conservation status, among others.

Now that I had the basic structure in mind it was time to get started. The easiest way to get started when building a gem is through bundler by running $ bundle gem GEMNAME, so that’s what I did.

$ bundle gem sea_life

This creates a scaffold directory for our gem and initializes a git repository, nice! The files automatically generated by bundler were: .gitignore,, Gemfile, LICENSE.txt (if you decide to use MIT license),, Rakefile, bin/console, bin/setup, lib/sealife.rb, lib/sealife/version.rb, and sealife.gemspec.

Since I knew I wanted to have an executable for my gem, I went ahead and created one in bin/sealife. I knew I wanted to keep that as simple as possible so I wrote a single line of code in it: (other than the shebang, and defining dependencies)

Given the way I wrote that line of code, I knew that my next task would be to create a class named CLI and write a method #call for it. I quickly realized I’d be needing Catergory and Animal classes as well, so I went ahead and wrote those as well. This bring us to the Scraper class, which actually does most of the work for this gem.

The scraper would go to Oceana’s website and scrape the information for the Category and Animal classes. If you are unfamiliar with scraping, it is the process of retrieving the HTML of a webpage and extracting information from it. I used Nokogiri in the scraping process. Nokogiri::HTML(html string)

After a bit of trial and error I eventually got everything working. I decided to publish my gem to RubyGems. This was made pretty easy by updating the information in the sea_life.gemspec file and running $ gem build sea_life.gemspec in the terminal to pack up the gem, and then running $ gem push sea_life-0.1.0.gem to publish the gem.

If you would like to take a look at my gem you can install it with

$  gem install sea_life

You can also take a peek at the code in its GitHub repository.