Creating a Ruby CLI Gem

My experience writing a simpleRuby Gem that scrapes NHL player stats from hhtps://quanthockey.com/

I began working on this gem using using the guides at: https://guides.rubygems.org/make-your-own-gem/

The repo for this project can be found here: https://github.com/nichol88/nhl_stats

With the challenge of creating a web-scraping CLI gem, I decided that I would go for professional sports data, seeing as how they would most likely be easily accessible on the internet. The site I used is: https://www.quanthockey.com/nhl/records/nhl-players-all-time-points-leaders.html

I began working from the CLI using fake, hard-coded data, so that I could get a feel for what my end goal is. I wanted the interface to display a list of Players, which I could then choose from, in order to get more info about that player. I named my project ‘nhl_stats’, with the following basic structure:

nhl_stats
├── bin
│   └── nhl-stats 
└── lib
    └── nhl_stats.rb
    └── nhl_stats
        ├── cli.rb
        └── player.rb
        └── scraper.rb

My NHLStats::Scraper class is responsible for obtaining the data from the <table> on the website, and also for creating Player objects for each row in the table, calling the Player.save method on each, so that they are accessible with Player.all.

The NHLStats::CLI class handles the user interface, prompting the use to enter one of a few choices such as list, exit, or a number to get more information. If the user chooses a player by entering their corresponding rank, the NHLStats::Scraper class will once again retrieve information from that player’s unique URL. Each player’s URL is stored in an instance variable, @url, when it is initially scraped from #scrape_all_top_players. It is scraped from the ‘href=’ attribute of the anchor element holding the player’s name (and link). So, a Player object is passed into NHLStats::Scraper.scrape_player(Player_object), which adds an additional instance variable to the object, @bio.

The NHLStats::Player class gives Players the ability to display their stats, using the #display method. The class method .list_all_players accesses the @@all class variable to call the #display method on each player that has been created.

The next step in development will be to allow the user to sort by different stats, and also to access more lists, for example allowing the user to choose stats from only specific seasons.

Here is a 30-minute video of me during the coding process: https://www.youtube.com/watch?v=zDDjVPKNI7Q

Leave a comment

Design a site like this with WordPress.com
Get started