Quick Rails!

November 22nd, 2006 at 3:30 pm (web programming, ruby, rails, tutorials)

A quick reference for creating a Rails site. Not a complete introduction. More of a cheatsheet. Here’s how to build a sample web application — a web design portfolio:

  1. Host a domain on a server with Rails support (e.g. Dreamhost shared hosting).
  2. Create three MySQL databases. Call them portfolio_development, portfolio_production, and portfolio_test.
  3. Create the Rails application skeleton (folder structure, config files, etc.).
    [host]$ pwd
    /home/username
    [host]$ rails portfolio
    create
    create app/controllers
    create app/helpers
    create app/models
    create app/views/layouts
    ***
    create public/stylesheets
    ***
    create config/database.yml
    create config/routes.rb
    ***
    create script/generate
    ***
  4. Configure your new skeletal app.
    1. Edit config/database.yml — set up database hostname, username, and password.
    2. Edit config/routes.rb — direct the root to “admin”: change line 14 to:
      map.connect '', :controller => "admin"
    3. Link from webroot (here, a folder called “domain.com”) to rails public directory (”portfolio/public”). This is good for security. We don’t want our source files to be under the webroot, where they may accidentally be exposed. ls -l will confirm that we’ve correctly created the link.
      [host]$ ln -s ../portfolio/public domain.com/portfolio
      [host]$ ls -l domain.com
      total 176
      ***
      lrwxrwxrwx 1 username unixgid 16 2006-11-22 13:40 portfolio -> ../portfolio/public
      ***
    4. Rename index.html to index.html.old.
      [host]$ cd portfolio
      [host]$ mv public/index.html public/index.html.old
    5. Check the setup by browsing to http://domain.com/portfolio — which gives an error. That’s expected, though, because we haven’t created the “Admin” controller that it needs.
  5. Create the database table needed for our app. Save the following as db/create.sql and execute it on portfolio_development:
    drop table if exists designs;
    create table designs (
    id int not null auto_increment,
    title varchar(255) not null,
    about text null,
    image varchar(255) not null,
    caption varchar(255) null,
    primary key (id)
    );
  6. Generate a scaffold. Rails will look for the corresponding table, and automagically give us CRUD (Create, Retrieve, Update, Delete) functionality for it!
    [host]$ ruby script/generate scaffold Design Admin
    ***
    create app/models/design.rb
    create test/unit/design_test.rb
    create test/fixtures/designs.yml
    create app/views/admin/_form.rhtml
    create app/views/admin/list.rhtml
    create app/views/admin/show.rhtml
    create app/views/admin/new.rhtml
    create app/views/admin/edit.rhtml
    create app/controllers/admin_controller.rb
    create test/functional/admin_controller_test.rb
    create app/helpers/admin_helper.rb
    create app/views/layouts/admin.rhtml
    create public/stylesheets/scaffold.css

    “Design” is the name of the model, “Admin” is the name of the controller. Now that we have created the AdminController, we should see something cool at http://domain.com/portfolio! It’s our bare-bones (but working!) application.
  7. Time to pretty it up. Let’s customize the listing view.
    1. Edit app/views/admin.rhtml to something like this:
      <div id="wrap"><div id="wrap2"><h1>Design List</h1>
      <%
      odd_or_even = 0
      for design in @designs
      odd_or_even = 1 - odd_or_even
      %>
      <div class="ListLine<%= odd_or_even %>">
      <div class="ListActions">
      <%= link_to 'Show', :action => 'show', :id => design %>
      <%= link_to 'Edit', :action => 'edit', :id => design %>
      <%= link_to 'Destroy', { :action => 'destroy', :id => design }, :confirm => 'Are you sure?', :post => true %>
      </div>
      <h3 class="ListTitle"><%= h(design.title) %></h3>
      <div class="ListImage">
      <a xhref="<%= design.image %>"><img xsrc="<%= design.image %>"/></a><br/>
      <span class="ListCaption"><%= h(design.caption) %></span>
      </div>
      <span class="ListAbout"><%= design.about %></span><br/>
      </div>
      <% end %>
      <%= link_to 'Previous', { :page => @design_pages.current.previous } if @design_pages.current.previous %>
      <%= link_to 'Next', { :page => @design_pages.current.next } if @design_pages.current.next %><br/>
      <%= link_to 'New design', :action => 'new' %>
      </div></div>
    2. Edit public/stylesheets/scaffold.css to something like this:
      body { background-color: #AAA; color: #333; }
      ***
      .ListTitle { color:#244; font-weight:bold; font-size:x-large; }
      .ListAbout { color:#244; }
      div.ListImage { float:left; width:173px; margin:0 10px 0 0; }
      div.ListImage img { width:173px; border:none; }
      .ListCaption { font-style:italic; font-size:x-small; }
      .ListActions { font-size:x-small; text-align:right; padding-left:1em; float:right; }
      .ListLine0 { background: #D3E9CB; }
      .ListLine1 { background: #F7F9DF; }
      .ListLine0, .ListLine1 { padding:10px; border:2px solid #333; margin:20px; }
      h1 { text-align:center; }
      #wrap { width:787px; margin:10px auto; background:#FFF; border:4px solid #444; }
      #wrap2 { padding:10px; }
    3. Look at your pretty, pretty site and think of the possibilities.

Comments

Ruby on Rails :: Welcome to the Twenty-First Century. You will like it here.

November 16th, 2006 at 1:10 am (programming, web programming, ruby, rails, tutorials, reviews)

Herein, and hereinafter, I learn Ruby and Rails. They are elegant, they are beautiful, I am excited.

Ruby :: Overview

Ruby is a modern programming language. It is powerful and extensible like LISP and Python. It is forgiving and flexible like PHP, concise and coherent like Python. End your line with a semi-colon — or don’t. An ellipsis is three dots, but two is ok — we know what you mean. Need a variable? No need to declare it, no special symbol to mark it; just use it.

ruby = "A modern programming language which you will love."
ruby_adjectives = [ "modern", "powerful", "flexible", "concise" ]
ruby_adjectives << [ "clean", "elegant" ]

Ruby’s conventions reflect the collective common sense that programmers have developed through trying times. For examples, naming conventions just make sense: Little things — local, ephemeral variables and methods — use lowercase. Big things — modules, classes, constants — use uppercase. Lowercase names use underscores to split words, and uppercase names use camelcase words.

message_to_readers = "Please comment!"
DesiredCommentCount = 5
if (BlogPost.comment_count < DesiredCommentCount) print message_to_readers

Don’t just take my word for it that Ruby has so many redeeming qualities, try it out for yourself with this interactive tutorial.

If you’re too cheap to buy the canonical introductory Ruby text, I heartily endorse Why’s (Poignant) Guide to Ruby, a well-written and humorous guide which uses mnemonics brilliantly and effectively to not only introduce Ruby, but make it intuitive. Beginning programmers, especially, would do well to read it.

Rails :: Overview

Rails gives you a skeletal web application out of the box (the design of which incorporates many, many design principles learned the hard way over a span of decades) and tools to make working with it much, much easier. Rails is opinionated — it makes (good) infrastructure decisions for you, leaving you to think only of the application level — once you’re mastered Rails, that is! This is a prime example of abstraction, and is analogous to the divisions between layers in the TCP/IP stack and between kernel, drivers and programs. Asking a programmer to create the infrastructure, presentation, and functionality of a web application is a lot like asking for a kernel and a graphical user interface to go with the program they want.

It’s clear that only a select few programmers need to be under the hood creating infrastructure and tools — the rest should build application logic and user interfaces. Presentation is rightly placed in the hands of the specific programmer or designer, supported by countless templates and widgets. The application logic is up to you. Let Rails be your infrastructure, and you will have the pleasure of working with the Ruby programming language, a very well thought out Model-View-Controller (MVC) architectural pattern, and the revolutionary Prototype Javascript toolkit.

Model-View-Controller Pattern

Decouple data representation, application behavior, and presentation. Orthogonal design: it’s a good idea. The upshot is, when you change something you should be able to change it in one place — not here, there and everywhere. Rails keeps layouts in one place, data models in another, controller operations such as Create, Retrieve, Update and Delete (CRUD) elsewhere, and views still elsewhere (a library might have “author”, “book”, and “genre” views, which are just different ways of looking at the data).

Resources

Recommended reading. I’ve only included the good ones.

Dead Tree Books

Online References: Big

Online References: Small

Additional Tools

Next up: I try to build a quick and dirty rails app. Hilarity ensues.

Comments

Close
E-mail It