Department of Engineering

IT Services

Ruby on Rails

Ruby

Ruby is a language installed on our central system. To use it interactively, just type

   irb

At the prompt type

   6+7

and press Enter. You'll get 13! Better still, you can type

   i=7
   6+i

and still get 13. Note that you don't have you say that i is an integer. In fact, you can carry on with

  i="test"

This flexibility is sometimes called "Duck Typing", apparently - if something behaves/tastes like duck, treat it as a duck. If a variable acts like a string then use it as a string. Fortunately Ruby has ways of getting objects to tell you what class they currently belong to.Typing

  i.class

will tell you that i is currently a string.

Ruby is Object-oriented. You can do

   i.length()

like you can in C++, etc, to find the number of characters in i. In some languages (Java, C++) some things aren't objects, but in Ruby everything is, even literals. You can do

   "test".length()

to find the length of the string. And of course you can create objects - by inheritance if you wish. You can even redefine classes (it's called "Monkey Patching", apparently). The next example shows how to add a new member function (called odd) to the standard Integer class.

  class Integer
     def odd?
       self & 1 == 1
     end
  end

  puts 7.odd?

Ruby has all the usual decision-making structures - e.g.

   i=7
   if (i<10) then
     puts "i is small"
   end

You can create loops by using for, while etc. Also Ruby supports various operations that can replace explicit loops. E.g. you can do

   numbers = [*1..10]
   odds=numbers.select{|x| x%2==1}
   odds.reverse

You can also create functions.

   def twice(n)
      2*n
   end
   # the next line calls this function, using the puts command to print 
   # the output onto the screen
   puts twice(5)

Working interactively becomes tedious. If you put some of this code in a file called program.rb and type ruby program.rb you can run the code. Better still, if the first line of program.rb is #!/usr/bin/ruby and you make the file executable, you can run the code just by typing ./program.rb

If you're used to Python, C#, Java or perl you'll notice quite a few similarities with Ruby.

Ruby on Rails

Ruby on Rails is a way of using Ruby as part of a collection of files to produce interactive web pages that access databases. It tries to automate as much as it can, producing dozens of files for you behind the scene. If you're starting from scratch and you're happy with the defaults, you can write applications quickly. It's used by Twitter!

Re workflow, it encourages a way of working that assumes programmers will Develop, Test and Deploy (there are different frameworks for each phase). Structurally it uses the MVC (Model-View-Controller) pattern. The View is what you see on screen; the Model is the database (the 'back-end'); and the Controller is between the 2. The underlying database can be SQL, SQLite (no users, auth, ports), etc. The database is accessed via an interface called ActiveRecord.

Various template-producers can be used. ERb (ruby template engine) is the default. Erubis is faster and Haml more stylish. To create some files for a project called test you can do

  rails test

This creates (for me on linux and Macs) over 150 template files and folders, all contained in a folder called test. If you then do

  cd test
  ruby script/generate model recipe title:string instructions:text calories:integer

a few more files will be created - files to set up the database, files for unit testing, and some files needed for later migration. Now it's time to use rake (Ruby on Rails' version of make). Type

   rake db:migrate

creates a table in a database, giving output something like

(in /Users/tim/test)
== CreateRecipes: migrating ===================================================
-- create_table(:recipes)
   -> 0.0049s
== CreateRecipes: migrated (0.0070s) ==========================================

To try it out, type

    ruby script/server

which might give output rather like this

emac:test tim$ ruby script/server
=> Booting Mongrel (use 'script/server webrick' to force WEBrick)
=> Rails application starting on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
** Starting Mongrel listening at 0.0.0.0:3000
** Starting Rails with development environment...
** Rails loaded.
** Loading any Rails specific GemPlugins
** Signals ready.  TERM => stop.  USR2 => restart.  INT => stop (no restart).
** Rails signals registered.  HUP => reload (without restart).  It might not work well.
** Mongrel 1.1.4 available at 0.0.0.0:3000
** Use CTRL-C to stop.

This starts a server. If you then go to http://localhost:3000/recipes in your browser you might see the page you've created. Note however that you shouldn't run a webserver within CUED without first checking with the webmaster.

Installing

The above example used a specially adapted web server program. In "Ruby on Rails" by Antonio Cangiano (Wiley, 2009) it says "deploying Rails applications is generally not much more difficult than developing them" (p.35), which sounds worrying. The web server hosting the pages needs to use mod_rails (phusion Passenger).

References