Debugging is such a journey. At the final leg of my project, I smirked that the code was running smoothly until my instructor found a small problem.
My project's goal is to use the API's data to help you find the right type of brewery in your state and city. When you enter in the state you live in, it prints out 5 sample breweries in the state.
However, after going through the whole code. The user is given the choice to return to "menu" or "exit." If the user chooses "menu," then the user can enter in a different state, city or type of brewery.
The problem my instructor discovered was that the first 5 breweries you listed after typing in your state would stay on the list. So when you return to "menu" and enter another state, it would give the original 5 breweries, PLUS the next 5 breweries from the new state.
-------------------HOW TO DEBUG THIS---------------------------------------
For several hours, I used binding.pry to see where it would create a new list. In my API folder, I was using an instance method to grab the API's data as an array and separate the array into nested hashes. I used this method 3 times to grab data from the API's base URL, state URL and city URL.
1st suspicion:
- I used this instance method 3 times in my CLI. Once in my initializer. Second time when I was creating a list for the state the user entered. Third time was when I created a list for the city the user entered.
Approach:
- Delete the instance method with the base URL because we are starting by looking for breweries in a specific state.
- Keep the instance method for the state
- Delete the instance method with the URL with the city because we are going to use the state URL to find the city, then the breweries in that city.
SO it ends up looking like this:
Since I got rid of the other 2 API instance methods, I got rid of the methods in my CLI and Brewery class folder, which used the deleted API instance methods.
Afterwards...Still the same problem
After doing all of this, the problem remains.
So I debug again. I put a binding.pry all over my CLI file
to see where my API method was repeating or being called
again so that the list of breweries for state is
duplicated.
Discovered:
- In my Brewery class, I had an instance method called "self.find_or_create_by_state" This method was creating objects from each nested hash and keeping the list. Basically creating a list and adding more created lists to the initial list.
SOLUTION!!!!!
The solution was so simple. Clear the original list before creating a new list.
Lesson Learnt
- Use binding.pry for each line of code to understand what the terminal is printing and how the code is printing that line.
Top comments (0)