Lesson Wednesday

As of now, each route in our record store's app.rb file ends with an embedded Ruby file being rendered. Unfortunately, this code isn't always very DRY. For instance, the following code shows up five times in app.rb:

@albums = Album.all

We can clean this up by using Sinatra's redirect method. A redirect simply triggers a different route. Here's an example:

delete('/albums/:id') do
  @album = Album.find(params[:id].to_i())
  redirect to('/albums')

Now once an album is deleted, the browser is redirected to the /albums route which will take care of retrieving all the albums for us. We can clean up our repeated code by using a redirect. Just make sure you don't put a redirect in the /albums route. Otherwise you'll get a too many redirects error from the browser.

We can DRY up code with a redirect:

redirect to('/[name of route to redirect to]')

Lesson 33 of 37
Last updated July 28, 2022