Saturday, December 15, 2007

Rails 2.0 and Scaffolding Step by Step

Rails 2.0 step by step.


Ruby on Rails 2.0 was released by the Rails core team on Friday, December 7th. There were quite a few changes in the 2.0 release, including the way that Rails generates scaffolding code. This change will probably cause trouble for people using tutorials written for previous versions of Rails. I hope this tutorial will help readers get started with Rails 2.0 and keep the community of Rails developers growing.

This is the first part of a multi-part tutorial. It will cover enough to get a scaffolded Rails application up and running under Rails 2.0.

This first installment of the tutorial will cover installing Rails and then using Rails to generate a new scaffolded application capable of the four basic database functions of creating, reading, updating, and deleting data. Later installments will cover replacement of scaffolding with actual code that will add to the model view and controller portions of the Rails application. The goal of this first part of the tutorial is to get new users over the changes made to scaffolding in Rails 2.0, and get the basic scaffolded application up and running.

Rails has proven itself to been excellent choice for the needs of most teams and projects.

Note:If you are following a detailed tutorial or book based on earlier rails version, it would probably be best to install an earlier version of Rails for use with that book. For example, the book Agile Web Development with Rails (AWDWR) by Dave Thomas and David Heinemeier Hansson is based on Rails 1.2.x. Instructions on how to install an earlier version of Rails are given later in this tutorial.

Use this tutorial to get started with Rails 2.0 and not older versions.

You will need to have MySQL installed on your system to follow along with this tutorial. You can search the web for the best way to install MySQL on your system, It won't be covered here.

Installing Rails 2.0
Installing Rails 2.0 is done the same way as in 1.2.x versions of rails. There are basically three steps to follow.
  • Install Ruby for your Distro or OS
  • Download and install Ruby gems
  • Use gems to install rails
the Get Rails link and the getting started with rails link have the best available information. Follow these links to get Rails installed on your system.

On my debian machine I used the following commands to install Rails 2.0.

Install Ruby:
Change to the superuser and use the debian package manager to install ruby
# apt-get install ruby irb ri rdoc build-essential

Install Ruby gems:
Then download Ruby gems, the ruby package management software, unpack it, change into the rubygems directory and run the file setup.rb as superuser:
$ tar -xvzf rubygems-0.9.5.tgz
$ cd rubygems-0.9.5
$ su
# ruby ./setup.rb

Use gems to install Rails:
The gem package manager can install Rails and all of its dependencies. As superuser issue the command:
# gem install rails --include-dependencies
INFO: `gem install -y` is now default and will be removed
INFO: use --ignore-dependencies to install only the gems you list
Successfully installed rake-0.7.3
Successfully installed activesupport-2.0.1
Successfully installed activerecord-2.0.1
Successfully installed actionpack-2.0.1
Successfully installed actionmailer-2.0.1
Successfully installed activeresource-2.0.1
Successfully installed rails-2.0.1
7 gems installed
Installing ri documentation for rake-0.7.3...
Installing ri documentation for activesupport-2.0.1...
Installing ri documentation for activerecord-2.0.1...
Installing ri documentation for actionpack-2.0.1...
Installing ri documentation for actionmailer-2.0.1...
Installing ri documentation for activeresource-2.0.1...
Installing RDoc documentation for rake-0.7.3...
Installing RDoc documentation for activesupport-2.0.1...
Installing RDoc documentation for activerecord-2.0.1...
Installing RDoc documentation for actionpack-2.0.1...
Installing RDoc documentation for actionmailer-2.0.1...
Installing RDoc documentation for activeresource-2.0.1...

Checking the version of Rails at the command line should give a version number for Rails:
$ rails -v
Rails 2.0.1

If you have trouble installing Rails follow the links above or go to the Rails Forum for help.

Using older versions
If you are using a book like AWDWR from the pragmatic programmers It would probably be best to use an earlier version of Rails. To install a previous version of Rails, use the following command:
# gem install --version=1.2.5 rails --include-dependencies
INFO: `gem install -y` is now default and will be removed
INFO: use --ignore-dependencies to install only the gems you list
Successfully installed activerecord-1.15.5
Successfully installed actionpack-1.13.5
Successfully installed actionmailer-1.3.5
Successfully installed actionwebservice-1.2.5
Successfully installed rails-1.2.5
5 gems installed
Installing ri documentation for activerecord-1.15.5...
Installing ri documentation for actionpack-1.13.5...
...

$ rails -v
Rails 1.2.5

Updating old versions of Rails
In order to update an older version of Rails to the most current, use the gem command:
$ gem update rails –-include-dependencies

Now let's see how we can get a basic Rails application up and running with a few commands

Using Rails 2.0

Getting started and checking out our installation
Creating a new project in Rails 2.0 starts out much like previous versions. This tutorial uses the example of creating an application to manage the inventory at a local Mom and Pop video rental store, Mom and Pop's Movie Exchange. We'll call the project 'exchange'.

We'll create a directory to keep our work in, change to that directory and use the 'rails' command to create the shell for the exchange application. A great deal of information will flash by on your terminal as Rails creates the basic structure of the application.
$ mkdir work
$ cd work
work$ rails exchange
create
create app/controllers
create app/helpers
create app/models
create app/views/layouts
create config/environments
create config/initializers
create db
create doc
create lib
create lib/tasks
create log
create public/images
create public/javascripts
create public/stylesheets
create script/performance
create script/process
create test/fixtures
create test/functional
create test/integration
create test/mocks/development
create test/mocks/test
create test/unit
create vendor
create vendor/plugins
create tmp/sessions
create tmp/sockets
create tmp/cache
create tmp/pids
create Rakefile
create README
create app/controllers/application.rb
create app/helpers/application_helper.rb
create test/test_helper.rb
create config/database.yml
create config/routes.rb
create public/.htaccess
create config/initializers/inflections.rb
create config/initializers/mime_types.rb
create config/boot.rb
create config/environment.rb
create config/environments/production.rb
create config/environments/development.rb
create config/environments/test.rb
create script/about
create script/console
create script/destroy
create script/generate
create script/performance/benchmarker
create script/performance/profiler
create script/performance/request
create script/process/reaper
create script/process/spawner
create script/process/inspector
create script/runner
create script/server
create script/plugin
create public/dispatch.rb
create public/dispatch.cgi
create public/dispatch.fcgi
create public/404.html
create public/422.html
create public/500.html
create public/index.html
create public/favicon.ico
create public/robots.txt
create public/images/rails.png
create public/javascripts/prototype.js
create public/javascripts/effects.js
create public/javascripts/dragdrop.js
create public/javascripts/controls.js
create public/javascripts/application.js
create doc/README_FOR_APP
create log/server.log
create log/production.log
create log/development.log
create log/test.log

Rails generates an entire framework for the application. Change into the newly created exchange directory and get to work.
work$ cd exchange
exchange$ ls -p
app/ db/ lib/ public/ README test/ vendor/
config/ doc/ log/ Rakefile script/ tmp/

Setting up the Model and Database Table
At this point many web frameworks would have to use database commands and DDL's to create the table we need to hold our movie inventory data, but thanks to Rails tight coupling between the data and the application we can use Rails to create and manage the tables our project will need. In the Model-View-Controller pattern of application design it's the model that regulates access to the data.

Rails can create the database and tables needed for the exchange project. Look at the file /exchange/config/database.yml, in it you can see the structure of the databases used in Rails:


You can see that there are separate tables for development testing and production. This separation helps in the development and maintenance of Rails projects.

In a difference from earlier Rails versions, Rails 2.0 will create the databases needed with the
command:
exchange$ rake db:create:all
(in /home/sean01/work/exchange)
exchange$

Starting the web server
Rails includes its own web server, so let's fire it up and see if we have everything working so far.
To start the rails webserver, WEBbrick, use the command:
exchange$ ruby script/server
=> Booting WEBrick...
=> Rails application started on http://0.0.0.0:3000
=> Ctrl-C to shutdown server; call with --help for options
[2007-12-13 12:01:16] INFO WEBrick 1.3.1
[2007-12-13 12:01:16] INFO ruby 1.8.5 (2006-08-25) [i486-linux]
[2007-12-13 12:01:16] INFO WEBrick::HTTPServer#start: pid=3637 port=3000


open your favorite browser and point torwards the URL http://localhost:3000
You should see something like:




Clicking on the 'About your application's environment' link will activate a little piece of AJAX code that lists the particulars of your rails application.




Notice that the default environment is development and not testing or production. This is just what we want during our development phase!

A ctrl-c in the terminal where the WEBbrick server is running will kill the server.

Old vs. New
The next steps show where differences between older Rails tutorials will become greatest. Older tutorials would script/generate a model then use the migrate file created to layout columns in the model's database table. Next you would script/generate a controller and add scaffolding.
This will fail in Rails 2.0.

In Rails 2.0 it will take fewer steps, but may be a little harder to follow because so much is accomplished with so few commands. First we need to think about the movie inventory table.


Start simple. Movies should have, at minimum a title, a description and a movie poster. Columns for other data like release date, rating or quantity on hand can be added later by altering the table through migrations. The next step is to create a model whose job will be to manage the data stored in the database.

The following command will generate the model, plus scaffolding, and the database migration
script needed as well as a controller, helper, and testing support files:

exchange$ ruby script/generate scaffold Movie title:string description:text one_sheet_url:string
exists app/models/
exists app/controllers/
exists app/helpers/
create app/views/movies
exists app/views/layouts/
exists test/functional/
exists test/unit/
create app/views/movies/index.html.erb
create app/views/movies/show.html.erb
create app/views/movies/new.html.erb
create app/views/movies/edit.html.erb
create app/views/layouts/movies.html.erb
create public/stylesheets/scaffold.css dependency model
exists app/models/
exists test/unit/
exists test/fixtures/
create app/models/movie.rb
create test/unit/movie_test.rb
create test/fixtures/movies.yml
create db/migrate
create db/migrate/001_create_movies.rb

create app/controllers/movies_controller.rb
create test/functional/movies_controller_test.rb
create app/helpers/movies_helper.rb
route map.resources :movies

Making Movies

The table will get created by the file in db/migrate/001_create_movies.rb . Let's look at the file
now:

This file will create a table called movies that will be tied to the model Movie. This is a Rails naming convention. A table people would match a model Person. A table cars would match a model Car. You can also see how the parameters we fed the script/generate command show up as table columns and types in this migration file.

Apply this migration to actually create the table with the command:

exchange$ rake db:migrate
(in /home/sean01/work/exchange)
== 1 CreateMovies: migrating ==================================================
-- create_table(:movies)
-> 0.0040s
== 1 CreateMovies: migrated (0.0042s) =========================================


To see what our work so far has produced, start the WEBbrick server with the command (if you didn't kill the earlier one use a control-c to kill it now):

/exchange$ ruby script/server
=> Booting WEBrick...
=> Rails application started on http://0.0.0.0:3000
=> Ctrl-C to shutdown server; call with --help for options
[2007-12-13 17:12:06] INFO WEBrick 1.3.1
[2007-12-13 17:12:06] INFO ruby 1.8.5 (2006-08-25) [i486-linux]
[2007-12-13 17:12:06] INFO WEBrick::HTTPServer#start: pid=4054 port=3000

point your web browse to the URL http://localhost:3000/movies and look at what we have
created.

It looks pretty bare, but we don't have any inventory yet. Click on the 'New Movie' link to start adding some movies to the inventory.

Add a title, description and path to the one-sheet and click Create.

Click the button labeled 'Back' (not the browser back arrow) to return to the main listing and add another movie.

This is still pretty bare bones, but we haven't even written any real code yet!

Oh CRUD!
In database terms CRUD is a good thing. Its an acronym for Create, Read, Update and Delete;
the four most basic functionalities of a data store. The exchange app has this basic functionality without writing one line of code. It isn't pretty at this point an does not have any interesting bits and pieces, but it does work.

What has been done so far?
  • Installed Rails
    #gem install rails --include-dependencies
  • Created an aplication with the rails command
    $rails exchange
  • Created the databases for the application with the rake command
    $ rake db:create:all
  • Used the script/generate command to create the scaffolding for the application
    $ ruby script/generate scaffold Movie title:string description:text one_sheet_url:string
  • Created the database table using the generated migration file
    $ rake db:migrate
  • Started the webserver with the script/server command
    $ ruby script/server
  • Pointed our web browser to the application and started entering and editing data
    http://localhost:3000/movies

Part 2
Next time we'll cover some actually coding. We'll look at how to use code in the Model, View, and Controller to alter the exchange application's look and functionality as well as learning about Rails built-in test support.

The purpose of scaffolding is to get started, but scaffolding should be replaced as we add code to our project. The usefulness of scaffolding is that we have an actual functioning application right from the start. We can make a change to the view, and test that nothing else breaks. Then repeat the process adding feature after feature until the application is ready for delivery. Its much easier to make changes to an application that already works than, it is to non-functional code that doesn't give any feed back.

Monday, June 25, 2007

Playa del Carmen

Vacation


I haven't been around to add to the blog for a while, I was on vacation with my family. I just couldn't pull myself away from the warm sunny tropical beach to fiddle around with the hotel's internet connection and spend time on a post or two.

We went to part of the Yucatan south of Cancun often called the 'Riviera Maya', in the town of Playa del Carmen. The water was warm and clear, the beaches have really made a comeback after last year's hurricane, and the food at our resort was fantastic. Our kids are too small to do some of the larger jungle excursions, but we visited the nerby bird sanctuary Xaman Ha with the family. My daughter and I went horseback riding in the jungle one day as well.

The resorts had three little Hobie cats guests could take out whenever they wanted, as well as several kayaks and sailboards. I tried to take out a cat as often as I could and truly enjoyed sailing the small craft through the clear caribean water between the mainland and Cozumel.

We stayed at the Viva Azteca. It is the smaller of two Viva resorts in Playa del Carmen. Viva is an Italian based company, and it showed through in the variety and quality of food served at the resort. Italians know how to eat.

Getting back meant a pile of e-mail to clean up, but a vacation from the computer, and from blackberries and cell phones is the best.

Thursday, June 7, 2007

Learning Ruby

An Introduction to Ruby


Ruby is a pure object oriented scripting language that runs on most personal computer operating systems including Windows, Linux, Mac OS/X, and BSD. Ruby also runs on most commercial Unix based operating systems as well. Ruby was created in 1995 by Yukihiro Matsumoto, usually referd to as "Matz".

Ruby's popularity grew steadily in the decade following its release. Ruby's growth and popularity are similar to the python language. Both languages have similar goals of simplifying programming. Many programmers have become proficient in both languages, and any perceived 'competition' between the two is usually positive and constructive. Matz mixed together some favorite aspects of other languages he worked with including Perl, Smalltalk, Eiffel, Ada, and Lisp to create Ruby. He wanted a more interactive language that was natural to work in. Something that seemed to 'fit just right'.

I came to ruby late, and through my use of Ruby on Rails in 2005. I've been a proffesional programmer for over a decade, and was most recently building web apps with Java. Rails was like a ray of sunshine in a dark world. The clean, simple approach to programming and the strict adherance to the MVC framework was a great change from the drudgery of configuring large scale Java apps. I was able to pick up Rails pretty quick and become proficcient, but to be better I will need to learn Ruby. So far I am happy to be a 'newbie' in such a great community!

Although I have learned a great deal of Ruby while working with Rails over the last few years, I am going to start over at the begining with Ruby. I've pretty much just picked up Ruby knowledge as I've gone along. I hope that a more rigorous approach to learning Ruby will help me be a better Rails programmer. I'm going to blog about my lessons in Ruby from the start, believing that taking the time to put what I'm learning in writing will help me to understand more.

Most likely I'll just be giving a few readers a nice chuckle at my incompetence.

In an interview with O'Reilly, Matz is quoted as saying:


"I wanted a scripting language that was more powerful than Perl, and more object-oriented than Python. That's why I decided to design my own language."

So far Matz, and the Ruby community are meeting that goal.

You can learn much more about Ruby at the Ruby Language site.

Ruby is free software and is available, either, uder the GPL or the Ruby Software License.



Getting started with Ruby



The first step you need to take in learning Ruby is to get Ruby on your machine.

Mac OS X



Mac OS X comes with Ruby pre-installed. If you don't have it, go to the Apple download site.



To install from source, go to the Source section.




Windows



Go to the ruby forge website and download the latest
one click installer and run it.



Linux



Linux distros usually have ruby installed already. If you need to install it, its best to use your distro's package management system:




Debian Gnu/Linux
 $ apt-get install ruby irb rdoc

RPM distros
Download an RPM from RPM Find and install with
 $ rpm -Uhv ruby-*.rpm
(You can also use something like yum, Yast, or apt4rpm if they are on your distro)

Gentoo Linux
 $ emerge ruby

Source
Go to the Source section.


FreeBSD



Ruby is part of the FreeBSD ports collection. You can install it with:


$ cd /usr/ports/lang/ruby

$ make && make install




Source (good for all UNIX)



Get the latest source code for Ruby ruby-1.8.6.tar.gz.

Un-tar the source code

$ tar -xvzf ruby-1.8.6.tar.gz


To install, cd into the resulting library just do the usual three step:


$ configure; make; make install




Your First Ruby Program


Use your favorite text editor to create a file called ruby_hello.rb. Type this one line in the file:


puts 'Hello World!'

save the file and run it at the command line with the command:

$ ruby ruby_hello.rb
Hello World!


You can also run the ruby code directly from the command line with the -e switch, just like in perl:


$ ruby -e "puts 'Hello world'"


Or use irb, the ruby interactive shell:


$ irb
>> puts 'Hello World!'
Hello World!
=> nil


Going back to our text editor, let's add some comments. Ruby single line comments begin with a #. Everything on the line after the # is a comment:


# the classic first program

puts 'Hello World!' #print a greeting


Multi-line comments are rarely used in Ruby. Multi-line or block comments are delimited with '=begin' and '=end':


# the classic first program

puts 'Hello World!' #print a greeting

=begin
This ruby program is

© copyrighted by me, 2007.

Or it would be if there

weren't already millions

of other programs exactly

like it, many of which are

in the public domain already.
=end


save the file and run it at the command line and you'll see the exact same result as before:


$ ruby ruby_hello.rb
Hello World!



So that's lesson one. Installing Ruby, writing and running the obligatory 'Hello World!' program to see if the installation went well. If you had any problems, check out the Ruby language page, or join the Ruby community and check in the mailing lists, chat rooms or with the local Ruby Users Group for help.

Tuesday, June 5, 2007

Ruby Yield

Yield is one of the most powerful concepts implemented in the Ruby programming language. Yield lets you branch from within a method and execute some external code, then return to the original code in the first method.

What's so special about yield in Ruby? You could get the same branch and return flow by just executing a method call in java, or a function call in C.

Heck, COBOL's PERFORM verb implements branch and return behavior. So what's up with yield?

Well, the behavior of what you branch to is set in stone with all those other techniques, but is undetermined until coded in Ruby. Yield is kind of like a place holder that says "I'm going to branch off and do something here, but I don't know what I'm going to do yet".

Maybe some examples will help make it more clear. Here is a Ruby method with some yields coded in it, then the code to invoke the method and the block of code to invoke when the yield is encountered:


def block1
puts "Start of block1..."
yield
yield
puts "End of block1."
end

block1 {puts "yielding..."}

Running this code would produce the following output:


Start of block1...
yielding...
yielding...
End of block1.

So block1 executes it's first line and prints "Start of block1...", then it executes the yields which branch to the block of code outside block1 but associated with it at run time, then comes back and prints "End of block1."

OK that's, fine but isn't that functionally the same as the following code:


def block2
puts "Start of block2..."
put_it("in put_it called method...")
put_it("still in put_it called method...")
puts "End of block2."
end

def put_it(text)
puts text
end

block2

Running this second set of code produces the following:


Start of block2...
in put_it called method...
still in put_it called method...
End of block2.

For the most part, these are pretty much the same. However without having to redefine any methods I could immediately execute the block1 method with a different block associated with it. The yield would branch and execute this newly associated logic:


block1 {require 'time'
puts Time.now.httpdate}

This produces the output:


Start of block1...
Tue, 05 Jun 2007 19:20:35 GMT
Tue, 05 Jun 2007 19:20:35 GMT
End of block1.

The hard coded function call in block2 forever ties the branching logic to the put_it function. To get different behavior you would need to either change the function call in block2 to call a different function, or change the behavior of the function put_it. This second way is brittle because it could break code elsewhere that calls put_it. The first is cumbersome and possibly brittle.

Ruby's yield is a wonderful construct.

What about when you don't want to branch, but want the other functionality in the block1 code to be executed? Can you just run the code without the associated block?

Let's see what happens. Running block1 without an attached block for the yield to associate to:


block1

This produces the result:


Start of block1...
LocalJumpError: no block given
from :3:in 'block1'
from :7
from :0

We get a 'no block given' error at line 3 in method 'block1'. Line 3 is our first yield in the block1 method.

What to do?

We can wrap the yield in an if statement and check for the presence of a block using the block_given? conditional. It returns true if a block was given with the method call, or false if not.

For this example I'll use a slightly more idiomatic way of checking for the presence of a block in ruby:


def block3
puts "Start of block3..."
yield if block_given?
puts "End of block3."
end

now if we run the code with a block:


block3 { puts "yielding" }

or without:


block3

It works both times producing:


Start of block3...
yielding...
End of block3.

and


Start of block3...
End of block3.


This will make your methods less brittle and more agile.

Ruby's yield is worth getting to know. You can learn more here and here. Many of Ruby's built in methods contain yields that allow you to associate blocks with them producing added functionality at run time.

Monday, June 4, 2007

The Beauty of Ruby

The Beauty of Ruby



I've been working more and more with Ruby on Rails. I'm hoping to be able to work full time with it in the next few years, but for now I'll just have to keep sneaking it into some of the bigger things I get paid to do.

Its too bad because Rails and Ruby could really help some of the clients I work for. I really haven't been this excited about a programming language since I learned C back in the Eighties!

One of the main benefits of Ruby on Rails is how opinionated Rails is. Rails does not try to be everything to everyone. It is trying to meet most of the needs of the average web app, but not trying to give into everyone's slightest whim. The coding needed to provide for most of what you need will be simple and straightforward with Rails. If you want more esoteric fluff, you can use J2EE. There are plenty of alternative solutions, but if 8 out of 10 apps you write fit in the middle, why are you forced to carry the luggage and infrastructure to support those few times the exotic stuff is needed.

Working with Rails is like working with a framework that imposes the KISS principle on your apps. It really results in savings and efficiency.

As I've worked more with Rails, I've begun to truly appreciate Ruby. Like many people in the last few years I came to Ruby through Rails. I started using Ruby as just another language. Most of what you know in any given language is available in any other. The biggest differences are between the procedural and the object oriented languages, but you might be surprised and how similar even these are in practice. Take Java for example. It is a fairly object oriented language. Its not pure OO, and it doesn't claim to be. Java's basic types are not objects. You know strings, floats, characters, and such. However Java is a pretty good example of a modern OO language. However you'll notice that quite a bit of Java was written by people who think like procedural programmers. take a walk through Java's network classes and you'll see the same kind of coding I was doing back when I learned C in the 1980's.

I shouldn't complain because I certainly wouldn't have done a better job. Heck, I wouldn't have done nearly as good a job as the people at Sun did.

Objectification


With Ruby everything is an object. You cannot cheat. You have to code in OO style. Better yet Ruby truly embraces its Object Oriented-ness! You often don't call a method on an object, the method invokes its own method on itself. For Java's class Math one of the methods is abs, a function that lets you compute the absolute value of a number. For example for an integer the function looks like:


Java code:


public final class Math {
...
public static int abs(int a);
public static long abs(long a);
public static float abs(float a);
public static double abs(double a);
...
}


You would use this method on an integer like this:


Java code:


public class MathExample{
public static void main(String[] args) {

int i = -7;
System.out.println("i is " + i);
System.out.println("" + i + " is " + Math.abs(i));
}
}


This is pretty standard stuff. It should be easy enough for any programmer to understand. For output you would get something like:

i is -7
|-7| is 7



What's not object oriented about that? Math is a class. abs is a method of class Math. Heck abs is even multiply defined so the same method can be applied to multiple data types! Math.abs() that is object oriented!

Yes it is.

So what's Ruby got?

Let's just look at How Ruby would do it first:


Ruby code:

puts 'i is ' + (-7).to_s
puts 'i is ' (-7.abs).to_s


The heart of that is when negative seven calls its method abs on itself

puts -7.abs


Yep, that's all folks. Remember Ruby is a pure object oriented language, so the integer '-7' is an object. The object '-7' is of type int and has a method called abs. -7 is calling its own method on itself! Lucky number seven.

The puts (for put string) looks like a normal function call with a function name followed by the object to perform the function on, but we could give objects a 'puts' themself method. You can see how we used the numeric object's 'to_s' method on itself to turn it into a string. The object that the puts function was operating on was not enclosed in parentheses as they are optional in ruby.

If you don't believe me, give it a try yourself. If you follow that link you will be on a site that lets you try out Ruby code at an irb prompt, thanks to Why the Lucky Stiff.

How does Ruby do it?


Well, lets look into the class definitions in the Ruby api and look up how abs is implemented in Ruby (remember Ruby is written is C):

/*
* call-seq:
* fix.abs -> aFixnum
*
* Returns the absolute value of fix.
*
* -12345.abs #=> 12345
* 12345.abs #=> 12345
*
*/

static VALUE
fix_abs(fix)
VALUE fix;
{
long i = FIX2LONG(fix);

if (i < 0) i = -i;

return LONG2NUM(i);
}


That's the implementation of the absolute value behavior for fixnums. All of Ruby's numeric types get an appropriate form of this behavior. Every numeric type in Ruby has the ability to calculate its own absolute value. As I use Ruby more and more, I am starting to truly appreciate the joys of object oriented programming.

There is truth in beauty.



Thursday, May 31, 2007

I attended RailsConf 2007 in Portland Oregon and had a great time. The Rails community is growing so large its unbelievable. Its starting to get all 'enterprisey' as well.

I wrote an article for Lxer summing up some of the events. I'll reproduce it here:



Railsconf 2007



  • "Make no small plans. They have no magic to stir men's blood and probably will not themselves be realized." -Daniel Burnham

  • "Form, ever, follows function." -Louis Sullivan

  • "Less is more." -Mies van der Rohe

What do these three have to do with Ruby on Rails and the second annual Rails conference in Portland?

Daniel Burnham and Louis Sullivan made their names designing and re building the city of Chicago after the great fire. Mies van der Rohe, later, gave the ultimate expression to the modernist style inspired by Sullivan. Their work was given life because of the development of a new disruptive technology, structural steel. This was the same steel developed to make the rails. The rails carried the goods, and the goods paid for their works.

Ruby on Rails was also born in Chicago. Rails was extracted from a working application because its creator, David Heinemeier Hansson (DHH), saw that he could re use the framework for other projects just as the steel rails were extracted from their original application and used to build skyscrapers. David and the team at 37Signals released Rails as an open source project and the Rails community has been building outward and upward ever since.


  • Rails lets you make big plans
  • Rails projects follow a form based on the MVC framework (their function)
  • With Rails 'convention over configuration' philosophy, less really is more

Rails is proving to be a disruptive technology in the development community, but the main disruption is due to the fact that web development does not have to be so difficult, and so barroque.

As with the first conference in Chicago, 2006, there was a pre-conference day of tutorials. The money raised for the pre-conference tutorials is donated to various charities. By the end of the conference more than $33,000 had been donated by the Rails community for various charities.

The highlights of the show included keynotes by Rails notables David Heinemeier Hansson, Dave Thomas, Avi Bryant, Michael Koziarski, Jamis Buck, David Black, Chad Fowler, Rich Kilmer and others. The two Davids were the bookends beginning and ending the conference. The keynote by DHH outlined some of the changes coming in Rails 2.0.

Tim Bray of Sun gave an interesting keynote. Sun has noticed Rails and is no longer ignoring or laughing. They don't intend to fight because they can sell servers for Rails clients just as well as for Java clients. The JRuby implementation should open some interesting new opportunities for developers.

Many of the other Rails community members, as well as Rails based companies gave keynotes and regular talks. There were four main tracks of talks each day with alternate tracks, BOF's, lightning talks and reject conferences day and night. Ze Frank's keynote Friday night showed that the Rails community is unique for its mix of developers and designers, and that the Rails community still maintains its irreverence even for all of the new ‘enterprisey'-ness.

A summary of the talks, coverage as well as photos and movies can be found:


Many of the talks feature the slides used. A quick trip to youtube or technorati and a search on Railsconf will show many more highlights showing up. (Some of the shots from Saturday's lunchtime marching band may not be suitable for the office).

Portland, Oregon is a beautiful city and the conference facilities are top notch. O'Reilly and the other major sponsors provided a fantastic venue. Last year's Railsconf was bursting at the seams and the team at Ruby Central and No Fluff Just Stuff did their best to accomodate, but the Rails community is growing too fast. This year's conference had three times the attendance of last year's.

The Rails community is thinking big and moving fast, but they are keeping Rails agile and light. If you are unfamiliar with Rails watch the videos available at the Ruby on Rails site. Rails is released under the MIT license.

Wednesday, May 30, 2007

fairleads blog

Fairleads are part of a ship's rigging. A fairlead is usually a block or a pully that helps to keep the jib sheets running smooth so you can control the jib. If this doesn't mean much to you it didn't to me either before last year. My wife and kids gave me sailing lessons for a Christmas present and I've been learning ever since.

In trying to think up a name for a blog the term fairlead popped into my mind. Its nice to have titles with more meaning to them.

On most sloop rigged boats the fairleads are mounted on rails so they can be adjusted back and forth on the boat. For the last year or so I've been working on Rails as well, Ruby on Rails. Since most of my work is done for client's internal use, I don't get any kudos for showing off my web apps. I hope to chronicle some of my adventures on Rails here.

I've had a web site since the late 90's, but I'm lucky if I update the thing every year or so. I've got to get back there and fix all the broken links. I'll get to that RSN, I'm sure :)

I'm hoping that with a blog I'll be a little more likely to keep things up to date. Maybe I'll post every three or four months! I'll try to keep up with new posts about sailing, Rails and my life in Linux as well as any other worthless things that happen to me and my friends and family.

Thanks for stopping by!