Sinatra Resource
After reading the chapter about Resources your
objective is to implement a resource members in Sinatra.
Exercise 5.1
Start by writing a Sinatra application that has an index and a show route:
- On
GETto/membersdisplay a list of member names, which are stored in a filemembers.txt. The erb template name isindex.erb. - Each of the member names is a link that points to
/members/:name(:namebeing the given member’s name) - On
GETto/members/:namedisplay a details page for this member (i.e. just show their name), and a link “All Members” that goes back to/members. The erb template name isshow.erb.
Exercise 5.2
Now add the new and create routes:
- Add a link “New member” to the
index.erbview, and point it to/members/new. - On
GETto/members/newdisplay a form thatPOSTs to/members. This form has one input element callednameand a submit button. Also, add a link “Back” that goes to/members. - On
POSTto/membersvalidate that the given name is not empty, and not already in our list. If the validation succeeds, redirect the user to/members/:nameand pass a success message by using the session. If the validation fails re-render the form and display an error message. - Make sure the success message is displayed in the
show.erbview.
Exercise 5.3
Next add the edit and update routes:
- In the
index.erbview add a link “Edit” next to each of the listed names, and point it to/members/:name/edit. - Also, add the same link to the
show.erbview. - On
GETto/members/:name/editdisplay a form thatPUTs to/members/:name. This form has the same elements as the form onnew.erb. Also, add a link “Back” that goes to/members. - On
PUTto/members/:namevalidate the given name. If the validation succeeds redirect the user to/members/:nameand pass a success message by using the session. If the validation fails re-render the form and display an error message.
Exercise 5.4
Finally add the delete and destroy routes:
- In the index view add a link “Delete” next to each of the “Edit” links,
and point it to
/members/:name/delete. - Also, add the same link to the
show.erbview. - On
GETto/members/:name/deleteprompt the user for confirmation: “Do you really want to remove the member [name]?”, and add a form that sends aDELETErequest to/members/:name, with a button “Remove Member”. Also add a link “Back” that goes to `/members/. - On
DELETEto/members/:nameremove the name from the filenames.txt, and redirect to/members
For the two forms on the edit.erb and delete.erb
views you’ll need to apply the trick from the
Faking HTTP verbs chapter.
If you have a hard time figuring out why a certain request does not work as expected try reading the logs of your Sinatra application (in your terminal). If that still doesn’t give you a good hint try inspecting the request in your browser’s web inspector on the network tab.