Customising controllers - new API

Posted by Tom on 2007-03-29

One of the nice things about Hobo is that you never have to write the seven boilerplate actions to get a basic CRUD controller (index, show, new, create, edit, update and destroy). The downside is that if you need to tweak the behaviour of one of those actions, there’s no code in your controller to tweak.

I’ve been addressing that issue by adding hook points, e.g. you can define create_response and invalid_create_response in order to override Hobo’s default responses. I’ve never been totally happy with that approach though - the number of such hooks is bound to grow until there’s a rather complex little API in there, which we certainly don’t want.

Today I’m having a go at a different approach. The index action in Hobo’s model controller is now as follows:

def index
  hobo_index
end

The hobo_index method (which is protected), can also be passed a bunch of parameters, so you could override index in your controller like this:

def index
  hobo_index :page_size => 10
end

Through parameters like that, you can customise pretty much everything. A common requirement is to include some eager loading in the ActiveRecord find:

def index
  hobo_index :items => Post.find(:all, :include => :comments)
end

Another trick - if you pass the items as a proc, the find will happen in a scope that handles pagination for you. (UPDATE: After some digging I’ve come across the idea, which I thoroughly agree with, that this is really an abuse of with_scope)

Baaad idea

def index
  hobo_index :items => proc { Post.find(:all, :include => :comments) }
end

So here’s the new way to achieve the same (and I renamed the :items parameter)

Good idea

def index
  hobo_index :collection => paginated_find(:include => :comments)
end

I think this approach is going to be easier to learn, while giving you a fine-grained choice between having Hobo do things for you, and having custom control.



(edit)