How I Built a Simple Command Line App in Ruby with ActiveRecord

puts "SUCCESS" else puts "ERROR: EMPTY DATA" end else puts "ERROR: INVALID DATA" end rescue RestClient::ExceptionWithResponse => e err = JSON.


response) puts "ERROR: #{err["status"]} #{err["name"]}" endendWhew! Glad to have that out of the way, as it was one of the biggest obstacles I faced while building out this project.

I then saved all the data I collected to a .

json file that I could seed my database with.

I created data for my other two relational models: a bunch of random names representing viewers I generated using the faker gem, and then a bunch of random show ratings amongst the viewers and shows by assigning a random integer between 1 and 5 to represent the rating.

Easy enough.

Once I had the database setup, I decided it would be best to be able to automate the process of generating fresh data.

For this I created a rake task:namespace :generate do desc 'generate all data' task :all do require_relative 'db/generate_shows.

rb' require_relative 'db/generate_viewers.

rb' require_relative 'db/generate_ratings.

rb' endendGreat.

Now all I had to do was invoke rake generate:all and then rake db:seed to populate my database.

I then moved on to creating my CLI.

I wanted to create a simple but robust interface that would allow the user to ask for help if needed, but wouldn’t bombard the user with unnecessary bloat.

I settled on using a series of nested submenus utilizing simple loop structures, as follows:loop do puts greeting input = gets.

chomp break if input == "quit" || input == "exit" case input when option1 loop do ## .

## do something ## .

end when option2 ## do something else puts invalid_input endendThe last thing I decided to do was to add an easter egg command to the main menu.

See if you can find it :)Go here to view the repo on GitHub.


. More details

Leave a Reply