Skip to content

Instantly share code, notes, and snippets.

@jeffwhelpley
Last active November 21, 2018 03:11
Show Gist options
  • Save jeffwhelpley/5f499cb3e405eef20959d548978a13e5 to your computer and use it in GitHub Desktop.
Save jeffwhelpley/5f499cb3e405eef20959d548978a13e5 to your computer and use it in GitHub Desktop.
class Cli
def run
# get the hash of fish data by scrapping the website (see further below)
fish_hash = self.get_fish_hash
# CLI stays in loop until user types quit
is_cli_active = true
while is_cli_active
# now show user the options that are available for them to choose from
self.show_user_options(fish_hash)
# now wait for the user to enter something
option = gets.strip
# this is just for debugging purposes and can be removed once program working
puts "option is #{option}"
# finally we show the user what they want depending on the option,
# the CLI may or may not be active anymore (if not, loop will break)
is_cli_active = handle_user_option(option, fish_hash)
end
end
def get_fish_hash
fish_hash = {}
# first get the html and parse it for the main fish div, Basics-Graphics-Frame
html = open('http://www.eregulations.com/massachusetts/fishing/saltwater/commonly-caught-species/')
doc = Nokogiri::HTML(html)
fishes = doc.css(".Basic-Graphics-Frame")
# now loop through each fish and pull out the fish name and description
fishes.each do |fish|
# the fish name is the h3 right under the .Basics-Graphics-Frame
fish_name = fish.css('h3').text
# check if nil or empty because we pick up some garbage
is_fish_name_empty = fish_name.to_s.empty?
if !is_fish_name_empty
# there are a lot of p tags under .Basics-Graphics-Frame; get all of them
all_p_tags_under_fish = fish.css('p')
# the first one is the description
fish_description = all_p_tags_under_fish[0].text
# the second one is always the location
fish_location = all_p_tags_under_fish[1].text.sub('Location: ', '')
# for now we are just adding to the has the name of the fish as the key
# and the description as the value
fish_hash[fish_name] = fish_description
end
end
# finall return the hash to the main function
fish_hash
end
def show_user_options(fish_hash)
puts "\nDid you catch a fish off the coast of New England? What type do you think?"
puts "Please pick from this commonly caught list:\n\n"
puts fish_hash.keys.join(', ')
puts "\nType in the name of the fish or type quit"
end
def handle_user_option(option, fish_hash)
# if what the user typed in is a key in the hash, then show them the desc
if fish_hash.key?(option)
puts "Here is the description: #{fish_hash[option]}"
true
# else if the user typed in quit, then say goodbye and return false, so
# loop will break and program will end
elsif option == 'quit'
puts "OK, goodbye"
false
# else some other invalid input, tell user to try again
else
puts "Sorry, invalid option. Try again"
true
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment