- Read Tutorial
Even though I work on professional projects each day, I'm still human and make mistakes. With that in mine I asked a senior developer, Michal Kwiatkowski, to review all of the code we've created up to this point. In this guide we'll clean up a few items that he brought to my attention.
Thankfully he only found two items that he recommended we fix, so that means we're in pretty good shape. So let's get started!
Cleaning Up Factory
The code review showed that our notification's second_notification
factory is pretty pointless. Notice how the values are the same? The whole point of having multiple factories is to be able to create different items so we can compare them and list them out. Our factory has identical values, so let's update the factory with some better data.
# spec/factories/notifications.rb FactoryGirl.define do factory :notification do phone "5555555555" body "My message" source_app "some_app" end factory :second_notification, class: 'Notification' do phone "4444444444" body "Another notification" source_app "some_app" end factory :outside_notification, class: 'Notification' do phone "3333333333" body "Third notification" source_app "different_app" end end
Implementing a Show View for JSON
Last on the refactor list is creating a JSON based show
view. Michal noted that it's a poor practice to say that we're rendering a show
view in the controller and not actually render anything. Let's clean this up a little bit. We already have a show.json.erb
file, so first let's update the controller's show
action so it has access to the notification
:
# app/controllers/notifications_controller.rb def show @notification = Notification.find(params[:id]) end
This will lookup a route such as http://localhost:3000/notifications/4.json
and will run a database query for a notification
with the id
of 4
and then store the notification in an instance variable for the view.
With that setup let's update the view file.
# app/views/notifications/show.json.erb <%= raw @notification.to_json %>
Now if you start the rails server and navigate to a URL that has an id
that you've created (you can check this in the Rails terminal) then your page will now look like this:
So now our code has been fully reviewed and I feel good about continuing with the build out. In the next guide we'll walk through API authentication.