The task: Contact manager
This week's task was to create a command line application to store, search and view the contacts, with the following features:
- Core: User should be able to enter a contact (name, email, phone number)
- Core: User should be able to see a list of all of my contacts in alphabetical order
- Core: User should be able to search for a contact by name and view their details
- Stretch goal: Save the contacts to a file
- Stretch goal: Load the contacts from that file when restarting the program
To complete the stretch goals, being able to save the contacts to a file was key. From Learn Ruby The Hard Way, I understood how to open, save, write to and close a text file. However, attempting to get the contacts to save in the text file in the right format was proving to be challenging.
Say hello to JSON
My team mate, Siobhan was working on saving contacts to a file too. She mentioned using JSON to do this, and kindly provided the link to a repo on GitHub where she had used it before.
This was my first time coming across JSON, and as a result the code Siobhan shared made no sense to me whatsoever. I needed an intro to JSON, and this video by Brad Traversy helped immensely:
## What Is JSON?
- Objects are written in key value pairs.
- Values must be a string, object, array, number, boolean or null, not a function
- Keys must be strings
.json()returns a promise
With that in mind, I revisited the repository Siobhan shared, and using her methods as a guide, created the following functions:
Implementing the above methods into my existing methods allowed me to store the contacts into a file 🎉
The next challenge was getting the contacts to be displayed in alphabetical order by first name. I couldn’t work out how to sort it alphabetically in the file.
I had the opportunity to share the issue I was experiencing with Ashley and Justyna. They advised me to find a way to import the contacts in the file to an array in my contact class. Well, that worked perfectly 🎉😲
Task completed! Here’s the repository for my Ruby Contact Manager: https://github.com/ellehallal/ruby_contact_manager