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:

app.rb
@albums = Album.all
erb(:albums)

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

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

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]')
end

Lesson 33 of 37
Last updated July 28, 2022