Video icon 64
Learn to Code. Start your free trial today.
Advertisement

Ruby on Rails for Designers

by
Student iconAre you a student? Get a yearly Tuts+ subscription for $45 →

Ruby on Rails is an open-source web framework that's optimized for programmer happiness and sustainable productivity. It lets you write beautiful code by favoring convention over configuration.

This is the way Ruby on Rails promotes itself - but in my words, it is an incredible framework that can really make your life much easier. You can learn more at their site http://rubyonrails.org

Step 1- Installing Ruby on Rails

Installing Ruby on Rails (also often shortened to RoR) is fairly painless on most systems, but you will need to be comfortable opening up the terminal. The Ruby on Rails download page provides links to get started, and I will reproduce them here to save you a bit of time. Just as a note, these are the places to get Ruby, which is what Rails is programmed in, and we will be installing Rails in a minute. To learn more about the language, review the Ruby site

  • Windows: One-Click Ruby Installer (I recommend using 1.8.6-26 Final Release)
  • Mac OS X 10.4: Ships with broken Ruby but you can follow the amazing guide by Dan Benjamin
  • Mac OS X 10.5: If you install the Developer Tools from Apple you will be set. Try either your installation discs or Apple's Developer Site and download Xcode
  • Linux: While this may vary for each distribution, you will need to install ruby, irb, & rdoc

Now that we've downloaded Ruby, make sure you have RubyGems, which is a package manager for Ruby.

Ruby Package

To test if you have RubyGems, run the following in terminal:

gem -v

As of this writing, 1.3.2 is the latest version. To update if you don't have the latest version, run the following, and if you are on a Mac, put sudo in the front.

gem update --system

If you won't be using RubyGems, follow these steps:

  1. Download the latest release of RubyGems here.
  2. Extract the package
  3. Change into the directory in your terminal (cd is the command)
  4. Run this in the terminal: ruby setup.rb (Add sudo in front of the command for Linux & Mac OS X users, you will also need to continue that for all gem install commands)

If you have a Linux system, you should be able to install RubyGems through your package manager, but I prefer the method above. If you have any more problems, check out the installation documentation at the RubyGems site.

Installing Rails

Now that we have the latest version of RubyGems, let's install Rails:

gem install rails

It will take a few minutes to install Rails and all of its' dependancies.

Step 2 - Creating an Application

So now that we have Ruby, RubyGems, and Rails installed, let's create a project! To create a new project, you will use the Rails command to create new projects. We will create a simple project named "blog." Note: This will create the app folder in the current directory you are in terminal, so make sure you change into the directory you want the app to be stored in.

rails blog

You should see something like this fly by:

Next, open the project in your favorite text editor/IDE. I personally love TextMate, -while only for Mac OS X, there are some great clones which are also available.

Folder Structure

The folder structure of a Ruby on Rails will look similar to the following:

There are three folders any developer or designer will need to work with on a daily basis: the app, config, and public folders. Please review the short explanations for each of the folders:

  • app: This is where your application's logic lives.
    • controllers: This is where Rails looks for the controller classes. In short, these receive the requests.
    • helpers: Helpers live in this directory and assist the controllers, models, and views
    • models: Each of these basically represents a table in the database, so finding information and setting up your application is dead simple
    • views: what the user sees
      • layouts: these are each of the layouts you can define a controller to use. Makes templating very easy.
      • all the other ones: While in our application we currently don't have any, each of the other folders that will be in this folder represent and relate back to the controllers, and the files that will be in here correspond to the actions in the controller
  • config: This folder holds all of your app's settings. Some specific files:
    • database.yml: This file holds your database settings
    • environment.rb: This file holds the Rails settings for your application
    • environements/: This folder holds the configuration settings for each of the specific environments: development, test, and production
    • routes.rb: This file holds the settings for the URL schema, as well as specific URL and where to send the requests
  • db: This folder will end up holding your database (if you use sqllite), your database schema, and all of your database migrations (changes to the structure)
  • doc: This folder will hold all of the documentation generated by rake doc:app
  • lib: The files in here contain application specific code that doesn't belong in your controllers.
  • log: Rails stores the logs in here, four of them. One for server specific stuff in server.log, and one for each environments.
  • public: This folder contains all of the files that will not change as much. Rails looks for files her before trying to go to a controller. Javascripts are stored in the javascripts folder, images in the images folder, and stylesheets in the stylesheets folder. Static files like robots.txt and other html files can also be stored here. Make sure you delete the index.html file because that will show up instead of what you want!
  • script: These scripts make your life a whole lot easier. The server script launches the development web server, and generate generates code.
  • test: The tests you write and the ones Rails creates for you are all stored here.
  • tmp: Rails stores any temporary files here.
  • vendor: Here you can install any Rails plugins (or libraries) made by third-parties that do not come default with the Rails distribution.

Step 3 - Getting your Hands Dirty

While the purpose of this tutorial is not to create an application, we will still do a bit of programming. Let's first create a controller named articles: (Make sure you have changed into the root of the Rails application)

script/generate controller articles

Now open up the file, and you should see this:

class ArticlesController < ApplicationController
end

All this code says is that we are defining a new class called ArticlesController that inherits from another class called ApplicationController. Now, we are going to create an action (referred to as a method strictly speaking in Ruby) name index, so when you go to http://localhost:3000/articles/ you will be shown something. Change your code so it looks like:

class ArticlesController < ApplicationController
	def index
	end
end

So now that we have an action, go to the app/views folder. We are going to create a view so when a user requests that URL, they actually see something. You may have noticed that there is a new folder in here named articles; this folder was created when we generated the controller. So, make a new file in the articles folder named index.html.erb. You may ask about the ending, the html refers to the type of file, and the erb refers to embedded Ruby as the templating engine. I personally prefer rhtml as it is a single ending, but that will be depreciated in Rails 3, which is planned to be released at RailsConf this summer. Put this into your new file:

The time now is <%= Time.now %>

The <%= %> tags may intrigue you. This tag is meant so that Ruby ouputs the results of the enclosed Ruby code. So this code will print the Time now. The other tag you will use in Rails is simply <%- -%>. This tag is meant for Ruby code that doesn't actually output anything, such as when repeating through items in an array.

Now we are going to create a layout to make this text beautiful. So create a file in the views/layouts directory named application.html.erb with the following in it:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
  <head>
    <title><%= h(@title) %></title>
    <%= stylesheet_link_tag 'application' %>
	<%= javascript_include_tag 'prototype' %>
    <%= yield(:head) %>
  </head>
  <body>
    <div id="container">
      <%- flash.each do |name, msg| -%>
        <%= content_tag :div, msg, :id => "flash_#{name}" %>
      <%- end -%>      
      <%= yield %>
    </div>
  </body>
</html>

First, before I explain the code, I do want you to know why we named the file application.html.erb. Rails will automatically load this layout every time unless otherwise specified. If you had named this layout "layout" then you would have had to add layout :layout to the top of the controller. This block of code has some important tidbits that you will want to know for when you are developing layouts.

  • <%= stylesheet_link_tag 'application' %>: This tag generate the CSS inclusion tag for the CSS file named application.css
  • <%= javascript_include_tag 'prototype' %>: This tag generates the Javascript inclusion tag for the Prototype javascript library. Prototype is the default javascript library that comes with Rails. You can also put :defaults (not in single quotes) instead of just prototype and Rails will load all of the defaults, :all would load all files in the public/javascripts folder.
  • <%- flash.each do |name, msg| -%>: This code and the code in the block means that for every item in the flash array, it will show a message to the the user.
  • <%= yield %>: This outputs all of the info from the individual view, and outputs in inside the template and sends this to the user.

Now, let's create a quick CSS file, named application.css in public/stylesheets, and put the following in it:

body {
  background-color: #111;
  font-family: Verdana, Helvetica, Arial;
  font-size: 14px;
}
#container {
  width: 75%;
  margin: 0 auto;
  background-color: #FFF;
  padding: 10px;
  border: solid 5px #999;
  margin-top: 20px;
}

Now, we have a very simple application for displaying the current time; hopefully, you should be more acquainted with the basics of Rails.

Step 4 - Finishing Up

You might be thinking, "This is cool and all, but how do I see the final product?" There is a terminal command that you need to run while in the base of the Rails application to start the local development server. script/server will start the server, normally on port 3000. Run the command and point your browser to http://127.0.0.1:3000/articles. You should see the following:

To stop the server select the terminal window and Control-C. This will stop the development server. As a note, make sure you never run a production server this way.

There is one last thing that I would like to show you. As I said before, the config/routes.rb file manages where requests go. Open up the file; we are going to make it so when you go to http://127.0.0.1:3000/, you see the same thing as before. Find the line, "# You can have the root of your site routed with map.root -- just remember to delete public/index.html." Under that section, add the following:

map.root :controller => "articles"

Save the file, and make sure you restart the web server. You will always need to restart the server whenever you create a new model, and change some other files that Rails stores in memory to speed up the server. Make sure you delete public/index.html, or just rename it. Now make sure the server is started and go to http://127.0.0.1:3000. You should see the same thing.

Conclusion

So now you should be a little more familiar with Ruby on Rails. I have also linked to some really great sites to refer to when developing with Rails. Have fun coding with Rails!

  • Railscasts put on by Ryan Bates is an amazing source of video tutorials, and you can always expect something great.
  • The Rails API is a great way to find more information about a subject you may not be entirely sure about.

Follow us on Twitter for more daily web development tuts and articles.


Advertisement