Thursday, 27 September 2007

Restricting to_xml RESTfully

If you want to restrict the XML representation of your model to just a few fields, use:
  def to_xml(options={})
options[:only] = [:id, :name]
super(options)
end

Replacing the array with whatever fields you want to restrict the representation to.

A couple of the other examples out there break the :index XML representation because they don't pass on the upstream options. This one is kind to REST.

Wednesday, 26 September 2007

Checking response codes

I'm getting up to full speed with Rspec at the moment. It's interesting how much is missing from Rspec_on_Rails compared to the standard test assertions - particularly when you start testing APIs.

Anyway here's a few quick helper method which you stick in spec_helper.rb within the Spec::Runner.configure block so that they are available to all your specifications.

The first set switches SSL on and off. I use them in the before blocks.
  def deactivate_ssl
request.env['HTTPS']='off'
end

def activate_ssl
request.env['HTTPS']='on'
end

The next patches a hole in the Rspec on Rails matchers, which seems to lack a wrapper around assert_response.

The helper function
  def status_code(type)
if type.is_a?(Symbol)
ActionController::StatusCodes::SYMBOL_TO_STATUS_CODE[type]
else
type
end
end

Then you can write the following specifications, e.g:
    response.response_code.should == status_code(:created)

Of course this would be better in a custom matcher. Over to you.

Thursday, 20 September 2007

A momentous day

I've tried to keep personal stuff out of this blog as much as I can simply to avoid boring my readers. After all everybody leads a life. However today is special - my eldest daughter, Amy, started school.

One of the great benefits of having kids is that they help scope the seasons and make you realise how fast time flies when you're having fun.

Sunday, 16 September 2007

Creating Static Home Pages in Rails

One trick I've not seen anywhere in my Google searches is to have Rails generate your static html pages for you.

However if you find that you have to build wrapper pages around the front of your application, then you can do a lot worse than use the tools of ERB, et al to reduce the duplication.

What I've used is a HomeController that looks like this:
# Static page generator
class HomeController < ApplicationController
caches_page :index, :donation

end

with a couple of routes at the bottom of routes.rb
  map.home '', :controller => 'home', :action => 'index'
map.connect '/:action/:id', :controller => 'home'

Now you merely create the views you require in views/home and add the name to the caches_page command.

Rails will then generate the static pages on first access for anything that doesn't have a more specific controller and has a view, and a 404 error for anything else.