Creating a simple Ruby Gem from scratch

By Nick Rodriguez

For our first project at Flatiron School, we were tasked with creating a Ruby Gem that has a command line interface and scrapes data from some website. I thought it'd be important to learn about the animals that are considered a priority for focusing conservation efforts, and figured that information would be described in a list somewhere. The information was, of course, readily available at the World Wildlife Fund's website. After a couple hours spent figuring out how to stream on Twitch, and a couple hours spent on development, the endangered_species_2 gem was born (there was already another endangered_species gem).

After a quick $ gem install endangered_species_2 and $ endangered-species, our gem calls to worldwildlife.org/species and pulls a list of animal names and links from this fun table.

https://www.worldwildlife.org/species
Priority endangered species on worldwildlife.org/species

An Animal object is created to hold each name and URL, then the list of animals is displayed in the terminal.

List of animals displayed in terminal
Animals displayed in the terminal

When an Animal is chosen, our gem then calls to that animal's unique facts page.

https://www.worldwildlife.org/species/polar-bear
Polar bear facts on worldwildlife.org/species/polar-bear

From this page, we can get a great set of attributes for our Animal object from the right column, and a description of the animal from the left column.

Animal attributes
Animal attributes

Since these attributes can be different for each animal page, I decided I wanted to have my Animal object accept a Hash (aka Dictionary or HashSet in other languages) of whatever attributes were found, and generate the appropriate reader and writer methods for each attribute.

Dynamic attribute definition
Dynamic attribute definition

Now, these attributes can be assigned as needed by calling the appropriate writer method. (Object.send is pretty cool, you can read about it here.)

Dynamic attribute assignment
Dynamic attribute assignment

Now that we have a bunch of information about the animal, we display it in the terminal.

Animal attributes displayed in terminal
Animal attributes displayed in the terminal

Animal description displayed in terminal
Animal description displayed in the terminal

This gem could easily be extended to pull more data from elsewhere on the page.

extension.PNG
More data to scrape? Yes, please!

Watch the entire development process from conception to publication on YouTube, view the source on GitHub, or check out the gem on RubyGems.org.


Faking Data - Seeding your database with mock objects