Ramaze by Example – Part 8: Deleting Tasks

November 22, 2008 at 9:53

Filed under: Computing — Pistos @ 09:53

This is part 8 of Ramaze by Example, a tutorial on web development. In Part 7: Checking off Tasks, we added to our application the ability to check off completed tasks.

We’ll round out the functionality of our app by adding a way to delete tasks from the list. As is commonplace when building a feature into an app, we think about implementation in terms of changes to the three parts of MVC. In this case, we don’t need to make any changes to the model, because M4DBI provides us with deletion functionality for free.

Modifying the view

In the list view, we add a link for users to click on to delete tasks:

(#{ A( 'delete', :href => Rs( :delete, task.id_ ) ) })

Nothing new here. I’m using A and Rs to build a link to a ‘/delete’ path, passing a task id as a parameter.

Modifying the controller

And of course, we need something to receive ‘/delete’ requests, so we add this to our controller:

def delete( id )
  Task[ id ].delete
  redirect Rs( :/ )
end

This should look straightforward, too. The delete method of MainController will be executed on requests for ‘/delete’, and it will take the id number passed as a parameter.

So we grab the task from the database using our Task model, then call the delete method on the task instance. When we’re done, we redirect back to the list, so there is no need for a delete.xhtml view.

Wasn’t that easy? Check out what we just did:

git checkout 8-delete-task
ruby start.rb

and surf to http://localhost:9001.

Review

Let’s review what we’ve learned while fleshing out the functionality of our application.

  • Ramaze can respond to requests when only a controller method or only a view is present (it doesn’t require both).
  • Controller methods should match controller paths. e.g. def create matches ‘/create’.
  • The request object acts like a Hash to provide access to POSTed parameters, keyed by field name.
  • h() is used to sanitize (escape) potentially malicious strings.
  • redirect is used to redirect to another site path.
  • A() is used to generate HTML <a> tags.
  • R() and Rs() are used to build site path strings relative to a controller’s mapped root. We can use these paths with h, A, redirect and anything else that needs a path string.
  • Controller methods can take arguments; these arguments correspond to a slash-separated list of parameters in a request.
    e.g. def check_off( id ) corresponds to a request like ‘/check_off/32′.
  • M4DBI model classes are extensible.

In Part 9: Layout, I will introduce a DRY way to have a consistent look across multiple web pages.

  • Share/Bookmark

No related posts.

1 Comment »

RSS feed for comments on this post. TrackBack URI

Leave a comment

You may use Markdown syntax in your comment.

Powered by WP Hashcash

Powered by WordPress.