RSS ? Recent Blog Posts

Blogs ยป Ruby on Rails
 

Get on Track

: Ruby on Rails Blog

Flexible Fixtures in Rails 2

by Myles Eftos

As Matt Magain pointed out yesterday, Rails 2.0 is now gold! Not a lot has changed feature wise from the PR (makes sense – features were frozen at that point), although it seems that the new improvements to fixtures managed to slip in to the final version.

Rather than having to map foreign keys in your fixtures using id numbers, you can use fixture names, which makes life a whole lot easier. So you can now write:

users.yml

joe_blogs:
id: 1
first_name: Joe
last_name: Blogs
mary_smith:
id: 2
first_name: Mary
last_name: Smith

websites.yml

website_1
id: 1
user: joe_blogs
url: “http://www.joeblogs.com”

website_2
id: 2
user: mary_smith
url: “http://mary.smith.id.au”

which obviously makes a lot more sense to a human reading it, especially when you have a large number of fixtures across many models.

Let me join Matt in congratulating the Rails core dev team for achieving this milestone – roll on Rails 3!

 

Rails 2.0.1 Released!

by Matthew Magain

While the SitePoint crew were busy sunning themselves by the pool on our annual Xmas trip, the Rails core team packaged up version 2.0 of the Ruby on Rails framework and released it on the world. I expect the team probably had a fairly stressful weekend putting out a few fires (understandable given this is a major release). The result of their hard work is that, after only a couple of days, version 2.0.1 is already upon us.

If you’re using Ruby Gems, update your Rails install by typing:

gem install rails –include-dependencies

Our resident Ruby guru Myles Eftos has covered what’s new in Rails 2 and how you can best prepare for upgrading, so be sure to read up before you take the plunge.

 

Cookies and sessions in Rails 2.0

by Myles Eftos

As we know, HTTP – the protocol that the web is built on is stateless – meaning that every transaction with the server doesn’t know anything about the previous transactions. To get around this, we use cookies to track session and emulate statefulness. Basically a cookie is stored on the users computer, which provides a key that the server can use to retrieve any session information.

In previous versions of Rails, we had a number of choices for our session stores – PStore, ActiveRecordStore, DRbStore and MemoryStore. PStore was always the default, which stored session data in a temporary file. This scheme did have a number of limitations such as race conditions in certain situations (That is, if two instances tried to write to the same session at the same time, your data could be come clobbered – storing a large information from an number of AJAX calls is one cause) as well as scaling issues – running multiple servers is pretty well impossible using PStore.

As a result most production systems would use one of the other stores, notably ActiveRecordStore which stores all of the session data in the system database.

To get around these limitations in PStore, Rails 2.0 will be …

 

Free Rails PDF: Only 3 Days To Go!

by Matthew Magain

Build Your Own Ruby On Rails Web Applications PDF GiveawayIf you haven’t taken advantage of the fact that Patrick Lenz’s introductory Ruby On Rails book is available as a FREE PDF, then you better act quickly as there are only three days left!

There’s plenty happening in the world of Rails development, and even before this giveaway I was of the firm belief that this book is the best and easiest way to get up to speed on the Ruby On Rails framework. Plenty of other books assume that you are an experienced web developer who is already writing unit tests and adhering to best practice MVC principles in some other programming language.

Not in this book. Patrick holds your hand through the basics and sets you up with an example application that, once complete, will give you a solid foundation from which you can further your Ruby and Rails skills.

Did I mention there are only three days to go? Seriously, go get it now. Even if you file it away for later.

 

Processing HTML with Hpricot

by Myles Eftos

In this world of Web2.0 mashups and easy API access, it is quite refreshing how easy it is to pull data for third party sites and re-mash it into something new. Unfortunately, not everyone has been bitten by this bug, so we as developers sometimes have to do a little more leg work to get the information we need. A common technique is called a screen scrape where your application acts like a browser and parses the HTML returned from the third party server.

Although this should be simple enough, anyone who has ever tried to do this knows the pain of dancing with regular expressions in an attempt to find the the tags that you need. Luckily, us rubyists have the Hpricot library which takes the hard work out of parsing HTML. Hpricot allows developers to access html elements via CSS-selectors and X-Path, so you can target specific tags really easily. And because it is written in C, it is pretty fast too.

Installation

Hpricot is a gem, so installation is as easy as:

gem install hpricot

The just require the library at the top of the ruby file:

require ‘hpricot’

Usage

Lets take this HTML snippet:

<html>
<head>
<title>Snippet</title>
</head>

 

Living on the Edge

by Myles Eftos

As I hinted at in a comment to my last blog post, release candidate 1 for Rails 2.0 has just been released with a number of improvements and bug fixes and in preparation for the final release it is recommended that anyone that is using the pre-release upgrades there applications – but how can you do that? Well it is much easier than you think, and you can be selective about which applications get the makeover.

Although you can reference the Rails libraries in a common path via gems, you can also install specific versions on an per-site basis. Rails will automatically look for a rails folder in the vendor directory – if it finds it, it will use that.

Freezing Rails

Probably the easiest way is to use the freeze rake task. Running the following in the root directory of you application should do the trick:

rake rails:freeze:edge TAG=rel_2-0-0_RC1

Piston

If you are more adventurous and want to play with the bleeding edge, you can use Piston to help you manage all of your rails plugins (including the core!). Now if you are a good little developer you should be using some sort of version control repository, my personal choice is subversion (SVN). This …

 

Preparing for Rails 2.0: Controller-based exception handling

by Myles Eftos

Since Ruby is a pure Object-Oriented Language, exceptions play a big role in the flow of control. Previously, you had the choice of rescuing exceptions at a local level or you could override the rescue_action method in your controller.

The former method gave you really fine-grained control of what to do in the case of an exception:

begin
user.save!
rescue ActiveRecord::RecordInvalid
render :action => ‘new’
end

In this case, if the ActiveRecord::RecordInvalid exception is raised (the save! method will raise this if validation fails) Rails will render the ‘new’ action. It became clear, though that adding begin/rescues around the same methods is pretty time consuming and not very DRY – which is where the rescue_action became helpful:

def rescue_action(exception)
if exception == ActionView::TemplateError
render :template => ‘errors/404′
else
super
end
end

This (rather contrived) example will trap any ActionView::TemplateError and render the 404.erb file in the /app/views/errors directory. You are able to drop that method into any controller (including app_controller), but again, there is a lot of work involved in setting them up, making sure each controller performs the correct action for a given exception, which is why Rails 2.0 introduces rescue_from.

rescue_from is …

 

Preparing for Rails 2.0

by Myles Eftos

Anyone that has used Rails 1.2.3, 1.2.4 or 1.2.5 may have noticed a number of deprecation notices in their development logs. Whilst these deprecated methods still work as expected in 1.2.x versions, you will come-a-cropper when you try to upgrade to Rails 2.0. So what do you need to do and what tools are out there to help you with the move? Glad you asked.

The first thing you can do it run your code through a code checker — Geoffrey Grosenbach has released a great rake task which digs through your code looking for the old methods. It will give you hints of how to fix the issues, but lets look at them a little more closely.

@params, @session, @flash, @env

As of Rails 2.0, you won’t be able to directly access the above instance variables. They have been replaced with methods, which makes customising their actions much easier. It also allows the internals of Rails to change without breaking the API. This is very easy to fix – just remove the @ in front of those variables – they will work exactly the same.

find_all, find_first, render_partial

In earlier version of Rails there were a number of grouped methods, that do very …

 

Rails 2.0 features: Multiple views

by Myles Eftos

The seed has been sewn for the next major release of the Ruby on Rails framework. Towards the end of last month, the Preview Release was announced and now that I have had a chance to play with it, I thought it timely to outline some of the new features.

Multiple Views

In version 1.2 of Rails, the respond_to block was introduced, which made serving up differerent data types, like XML or JSON really easy. All you needed to do was something like this:

def index
@stories = Story.find :all
respond to { |format|
format.html {}
format.xml {
render :xml => @stories.to_xml
}
format.json {
render :json => @stories.to_json
}
}
end

Then, on the web browser, if you appended the file extension (eg /stories/index.xml) and you would get the content delivered in the requested format. You could even …

 

Ruby on Rails: The art of simplicity

by Myles Eftos

Hi there, my name is Myles Eftos and I’m your new Ruby on Rails blogger! I’ve been hacking rails for almost two years now, building a number of online apps, such as my time tracking system: 88 Miles. I am constantly pushing for that Rails-zen state, that harmonious balance between simply beautiful code and powerful functionality.

For those of you yet to be bitten by the Rails bug, it is as close to web development heaven you are going to get (Yes, I’m a bit of a Rails-fan boy – you have been warned). I have worked professionally on just about every web platform out there, and Rails is by far my favourite – things that take hours in PHP take minutes in Rails. The completely self-contained development environment, built in database migrations and deployment system means that you can get a Rails application out the door before some of the other guys have finished setting up their XML configuration files.

The soon-to-be released version 2.0 of Ruby on Rails will once again re-enforce the simplicity and power of the framework with a number of improvements that will make the lives of the humble web developer just that …

 

Sponsored Links

SitePoint Marketplace

Buy and sell Websites, templates, domain names, hosting, graphics and more.

Follow SitePoint on...