Next → Fifth Step, getting dynamic Third Step, V, like View ← Prev

Fourth Step, C, like Controller

The last part of the MVC-paradigm is the Controller.

Wouldn't it be nice to have a way to add and remove items on our to-do list? Editing the model every time would be quite tiresome and limited.

Well, come along, I'll introduce you to Controller.

In the way MVC is structured, the Controller provides the data in a nice way for the View, removing all of the data-preparation and most of the logic from the templates. This makes it firstly simple to change the front end of your application and secondly provides excellent ways of changing the complete Structure of the Model or View independent from each other.

OK, enough of the theory, you will see the benefits in an instant. Go on and edit the file controller/main.rb.

The contents of it are like following:

class MainController < Ramaze::Controller
  def index
    @welcome = "Welcome to Ramaze!"
  end
 
  def notemplate
    "there is no template associated with this action"
  end
end

The only methods right now are #index and #notemplate. The relationship between the methods on the controller and the templates is 1:1, so the method #index is combined with the template index.xhtml. This combination is called an action.

Let's get back to editing and change the method #index to this:

def index
  @tasks = TodoList.original
  @tasks.each do |title, value|
    status = value[:done] ? 'done' : 'not done'
    @tasks[title] = status
  end
end

This will take care of the logic inside the template, which now should be changed to do following:

<html>
  <head>
    <title>TodoList</title>
  </head>
  <body>
    <h1>TodoList</h1>
    <?r if @tasks.empty? ?>
      No Tasks
    <?r else ?>
      <ul>
        <?r @tasks.each do |title, status| ?>
          <li>#{title}: #{status}</li>
        <?r end ?>
      </ul>
    <?r end ?>
  </body>
</html>

The rest of the template can stay the same.

Now, if you browse to http://localhost:7000/ again you will not notice any change, which is how it should be. The only change is that if there are no Tasks it will say so.

Some things you should know:

  • Instance-variables defined in the Controller are available in the View.
  • The return-value of the Controller does not matter if a template is present.

Next → Fifth Step, getting dynamic Third Step, V, like View ← Prev

 
Back to top
tutorials/todolist-4.txt · Last modified: 2008/06/13 18:57 by lel4866