Specials

Home > Specials > Columns

Pimp My Rails: The Rails Framework

walski on 04/05/2008 07.29 PM
(read 1427 times)

The pimping continues: In the last episode I've shown you how to setup a Rails environment on your local computer and we've created a first Rails application. Today we're getting into details of the Rails framework and it's principles.

Welcome back!

I promised to show you how easily a authentication system can be integrated in your Rails application, but we won't do that this week. My fault! But the article got to long and so we've decided on shifting this explanation to the next week's article. But now let's rock on!

First of all I would like to tell all the Windows fanboys out there about an interesting discussion, going on at the moment in the Ruby world, about the support of Windows as a platform for running Ruby. You find an interesting write-up about this here.

Ruby Inside
An excellent blog about what's going on at the Ruby community, written by Peter Cooper. It's frequently updated and features very well written articles. Check out the blog and maybe you'll find it worth to subscribe to the RSS feed.

Before we're going into the details of user authentication, it's important that you understand how a Rails application basically works.

Rails follows three main principles:

  1. Strict use of the MVC pattern
  2. DRY dogma (don't repeat yourself)
  3. CoC (convention over configuration)

All of these principles intersect at some point.

HTTP
Even if it's not necessary at all costs to know about the technical backgrounds, like the HTTP protocol, to develop a Rails application, it's a real good idea to do so, anyway! So if you're not familiar with HTTP try to read a little bit about it. Wikipedia might be a good start for that.

MVC - Model View Controller

This concept was first described by Trygve Reenskaug, 1979. Somewhen in the 1990s someone had the brilliant idea, that reinventing the wheel is the worst of all options and thought that what was right for the GUI development since more than 10 years, couldn't be so wrong for the relatively new web development. This was a wise guy. Unfortunately I don't know whom to thank for this great idea of returning to what was true before, but, take it for granted that MVC is terrific! :)

But what is it? Generally it means that your code-base is split up into three parts:

  1. The model: A model is an object of your program which handles the the logic of one specific domain of what your code tries to cover. E.g. a User or maybe a Monster or a Weapon. If you take a the user as an example, the model on the one hand represents all the information of the user, like his email address or nickname. On the other hand it offers you methods like login, resetPassword, etc. The model is the heart of your game.
  2. The view: A view is what you may know as a template. It is the presenting layer of the MVC pattern and you need it to define e.g. how a user is shown to the user of you website. If you would like to show a user's profile, the profile view will take a user model and render the HTML for the profile page. If you would like to show some high score lists, the high score view will take some user models, too but display these users in a different way as the profile view, it displays a high score list.
  3. The controller: The controller is the glue between the model and the view. Any HTTP request which hits your server will be processed by a controller. Maybe a user calls the URL http://example.com/high score/last-week. Then a controller will first fetch all the users, who made it into the high score last week. After that the controllers passes all this users to a view (the data which the controller passes to the view as a whole is considered as the model, as well). To finish the request, the controller will deliver the rendered HTML from the view to the user who requested the high score. People, coming from PHP, tending to bloat controllers until they burst! Be careful! Any domain specific code belongs into the models! Normal Rails controllers are usually real leight-weight.

DRY - Don't repeat yourself

This one is simple: NEVER EVER COPY CODE!

No rule without exceptions, but for 99% of your code take this advice from many really experienced Rails developers: If you come to a point in your code, where you would like to copy&paste from another method or class or whatever, go the extra mile, outsource this code, so that both places can call ONE method. Rails offers you good tools ease the pain of this extra mile and you'll be soooo much happier when you have to refactor and maintain your code. Actually this rule will help you in any programming language, you will ever learn, but the Rails community hypes it more, than any other language, I know and this is good!

CoC - Convention over Configuration

Unlike the DRY principle, CoC was somehow a new experience for many developers when they got to Rails. In the meantime many other popular web frameworks (like Django for Python and others) have adopted it or developed similar solutions independently of Rails, but it turns out to be a very good idea: Instead of confronting the developer with the necessity to configure every little aspect of the framework, Rails just asks you for your database host, user and password and anything else is ready, out-of-the-box! Don't get this wrong: You CAN configure everything, but in my experience you won't even touch 90% of all the options even for larger projects.

But Rails goes one step further with so called generators. These a little scripts which supports you at the creation and deletion of any kind of thing in Rails. Instead of just starting with a new file and then building a controller, model or view from that file, generators allow you to generate e.g. controllers or models. Such generated files already have the basic skeleton of a controller or model and you don't have to mess with the boring creation of infrastructure, the generators does this for you. And it goes even further with the creation of so called scaffolds which in fact are complete bundles of a model, a view and a controller which offer you the basic CRUD (Create/Read/Update/Delete) operations on the model. This should be enough theory for now. Let's get back to actual code!

REST
REST is a technique to make things easily accessible on the web and directly competes with complex web-service interfaces like SOAP.

Since it's 2.0 release, Rails really strongly encourages you to go the RESTful way. But we don't follow this recommendation through this tutorial. The simple reason for that is: MMOGs have to struggle a lot with bots and nasty scripts and it is one of the main concerns to keep control over your game. Opening it up with a RESTful architecture is like walking through ghetto with a glass case full of money...

But if you would like to know more about REST just head over to Gregg and Jason from railsenvy.com, they have a great video presentation where they explain REST in detail.


Your first controller and view

Now we're going to create our first controller. If you like, you can rename the "test_application" directory, which the rails command created for you during last weeks tutorial, to whatever you like. Then fire up your terminal, change into that folder and do this:

script/generate controller startpage

Cool, you see a list of files which the generator has created for you. The interesting file is the startpage_controller.rb in the app/controllers folder of your application. Open up this file.

Editor of choice
It's hard to find a perfect editor for Rails development. Here's a list of cool solutions:

While Netbeans and RadRails (which is based on eclipse) are real IDEs which give you maaaaany features, TextMate is a "simple" editor. But it's a real pleasure to work with it and it feels, unlike the IDEs, really lightweight. Check them out and decide what is the editor of your choice. Actually you can use any text editor. And there are many of them with Ruby/Rails syntax highlighting out there!

Now you should see something like that:

class StartpageController < ApplicationController
end

To display our first page we'll now add an so called action and after that the corresponding view. Edit the file like this:

class StartpageController < ApplicationController
def index
@test_variable = "Hello"
end
end

Technically the block between def and end is a method like in any other programming language. The name of the function is index. For Rails any method in a controller class (a class which derived from ApplicationController class) (the < sign after the class name is the same as the extends keyword in language like PHP and Java) is an action. An action can be called by an URL. The default behavior of Rails is, that any URL is built like this:

http://yourhost:serverport/controller_name/action_name/index_variable
Example:
http://localhost:3000/startpage/index

The controller_name is startpage in our case, the action_name is index and the index_variable is empty. This index_variable can be used to pass an argument to the action by the URL.

This: http://localhost:3000/startpage/index/5
is EXACTLY the same as this: http://localhost:3000/startpage/index?index=5

So the index_variable is just some eye-candy for the URL and it's accessible under the name index inside the actions. You can easily define more of such variables which are encoded in the URL and have different names than index, as well. But more on that routing topic later on.

Before we can try our controller we have to create a view for the index action! Go to the app/view/startpage folder of you app an create a new textfile in your editor named "index.html.erb". The file-extension of Rails 2.0 is "markup-language.renderer". In our case we would like to create a html file and the renderer we use is the default Rails renderer, named erb (embedded Ruby). You can imagine other file-extensions like ".rss.erb" of ".xml.erb". Don't worry about the renderer. Changing that is an advanced topic which isn't complicated, but isn't really needed at the beginning, too.
During this tutorial you will encounter the old file-extension format of Rails, which reads like this: "index.rhtml" This means the same as ".html.erb".

In the created "index.html.erb" you will write the HTML, that your controller should deliver to the browser. So let's start with a no-brainer:

Hi, I'm your brand new Rails application!

Save that. Now you need to start your server up and again, as described in part I of this tutorial. Just jump into the root folder of your application and enter:

script/server

Then call the newly created action in your browser, as described above: http://localhost:3000/startpage/index if you like you can also call this just by http://localhost:3000/startpage because index is the default action which Rails is choosing if no action is specified.

You should be able to see a friendly, white page with the "Hi..." text, you've entered above. Now lets spice it up.
In erb you not only can write plain text, which would be pointless, you can insert Ruby code in the templates, too. Some of you moan now: "Ruby code in a view, that's a violation of the MVC pattern!"... it depends! It depends on what Ruby code you'll write in the view ;) And believe me, it's easy to write code that doesn't violate the MVC pattern, especially if you keep an eye on avoiding this.

There are to techniques to insert Ruby code into your view:

  • <% 1+1 %> this evaluates the expression.
  • <%= 1+1 %> this evaluates the expression AND inserts it return value into the template.

So the PHP equivalents to that are:

  • or

Most of the time you will need the <% ... %> tag for if-clauses or something like that and the <%= ... %> tag will be used to insert something into your templates.
Let's play around with that knowledge and edit the index.html.erb file.

Hi, I'm your brand new Rails application! <% if @test_variable.size >= 5 %> YES! The test_variable is long enough! Here it is: <%= @test_variable %> <% end %>

Now you've to take a look at the code in the startpage_controller.rb file, we've edited above. There is this line:

@test_variable = "Hello"

This defines an instance variable named test_variable which holds the "Hello" string. Look at this PHP example

class SimpleClass {
public $var = 'a default value';
}
?>

The $var variable in this example is an instance variable. It is available to the instance of an object.

So our @test_variable variable is valid throughout the while life-cycle of an StartpageController instance. If we would have written:

test_variable = "Hallo"

(Pay attention to the missing @) the test_variable variable would only be available in the "index" method.
In Rails instance variables in controllers have a special meaning. They are used to transport information from a controller to a view. And this is, what we've done in our latest view modification. We just access the @test_variable variable and playing around with it a little. Now give this a try and mess around with the @test_variable = assignment in the StartpageController. You'll see, as soon, as the String gets shorter than 5 characters, the extra output in the view will disappear. To apply changes of the view or the controller to your running Rails application you have to do nothing, than just saving the files. The changes should be visible immediately when refreshing the page in the browser.

Web development with Ruby on Rails:

Pimp My Rails
Pimp My Rails: The Rails Framework
Pimp My Rails: The First Model
Rails Pimpin' Continues


Share   Subscribe

Comments

Advertisement
1 (1) Tendenz Khan Wars
2 (2) Tendenz Bulfleet
3 (3) Tendenz Tycoon Online
4 (4) Tendenz Mobstar
5 (5) Tendenz IceWars
6 (6) Tendenz Mythlands
7 (7) Tendenz Crimson Moon
8 (8) Tendenz ZeldereX Online
9 (9) Tendenz Holy-War
10 (10) Tendenz World of Dungeons
Amazon-Survival
Perfect 11...
Net-War
Coobico
Advertisement
How old are you?
< 18
18 - 24
25 - 34
35 - 49
> 50