Sunday, January 18, 2009

Ramaze Multiple Pages

Well, it wouldn't be too awfully interesting if all we could do was a single page no matter how easy it was to put it up. Here's a Ramaze program where we have multiple pages that is very similar to our "hello world" program.

require 'rubygems'
require 'ramaze'

# This example is based on the previous "hello world" example. All we've done
# is add two more methods to our MainController class that we will show "Page 1!"
# and "Page 2!" respectively.
class MainController < Ramaze::Controller

# You can access it now with http://localhost:7000/
# This should output
# Hello, World!
# in your browser
def index
"Hello, World!"

# You can access it now with http://localhost:7000/page1
# This should output
# "Page 1!"
# in your browser
def page1
"Page 1!"

# You can access it now with http://localhost:7000/page2
# This should output
# "Page 2!"
# in your browser
def page2
"Page 2!"


Once again, copy this into a text editor, save it as multiplepages.rb, and finally run it as either ruby multiplepages.rb or as ramaze mutiplepages.rb. After that you should be able to navigate to http://localhost::7000 and see "Hello World!". Additionally, you should be able to go to http://localhost::7000/page1 and see "Page 1!" or http://localhost::7000/page2 and see "Page 2!". You should also be able to go to http://localhost::7000/index and see "Hello World!" even though you don't actually need the "index".

What we're seeing here is that each method in a controller represents a view. You may have heard of MVC or Model, View, Controller architechture and Ramaze (as well as Rails) is built like this. We aren't seeing true "Views" yet but in a future post we will, ours are more implied. You can read more about the MVC architecture at on Wikipedia.

Go ahead and experiment with this code. You can add some more methods to the controller class or even play around with the text in each class (hint, try putting some HTML tags around the text, say h1 and see what happens.

Leave questions or comments in the comments section.

No comments:

Post a Comment