Tips for Your First CLI App

Joseph Kniskern
3 min readOct 8, 2020

--

The Faker gem

The Faker gem is an awesome tool to help seed a database. Essentially it pulls random info accordingly to be used as test data. That being said getting it setup for the first time can be a little tricky. To get started it needs to be required in the gem file and you need to run a bundle install. Once that’s done you can head over to your seeds file and get started. Faker will generate a single instance of test data each time its called so we need to wrap it in a times loop. Each instance can be saved as a variable and each variable can be assigned to a parameter of your new instance.

TTY Prompt & prompt.select

TTY prompt is incredibly useful in creating good looking, dynamic CLI applications. The prompt I used most often, and the one that took me a few tries to really get the hang of was prompt.select. What this will do is create a nice dropdown menu in your CLI app of selections to choose from.

It seems straight forward: you write prompt.select, and you pass in a string that’s your script ( for example “What would you like to do?” or “Please make a selection”), and an array that are the options ( %w( Good Bad Ugly) ). It becomes far more useful when you realize some more advanced ways of using .select. You can save the entire .select as a variable so you can use the selection in the many, many ways a variable can be used.

Aside from that a slightly different format of the .select is to use it with a do/end block. This gives you the ability to use a loop for your display options and save object_ids as procs to keep track of specific choices used in your application.

Refactoring your code.

Your app is working!! The thing is functionally sound and you’ve met the MVP requirements. Something you may notice is that along the way your code has gotten very messy. Do not fear refactoring is here! First things first go through your code line by line and make some notes about where you can make some formatting changes ( do you need all those elsif statements when a case statement could do the job just fine?). The next thing that can be done is taking all those sections and finding if you can just wrap them in a few methods. You can then create a new file that holds all these methods in a single class (this is called a singleton and should be used with some caution beyond the CLI app) and use the class name as a global variable to call these methods in your run file. Now you have a run file that’s nice and clean, and your other file you can section off with comments to make it even more readable.

Thanks for reading!

--

--

No responses yet