Resourcelogic

Beta warning: right now this plugin is in what I like to call a “semi-beta”. The only thing left to do is write documentation and add in the tests. I have already thoroughly tested this in a separate application, and am in the process of moving over the tests without having to pull over the entire rails application.

The purpose of Resourcelogic is to support a development style I created called “Contextual Development” (see contextual development below). This is an idea I’ve had for a while and finally decided to give it a try on one of my projects. It worked out great, and as a result, is probably the cleanest app I’ve built to date. So I decided to package this idea up and release it as Resourcelogic. This library spawned out of the resource_controller plugin by James Gollick, which is an excellent plugin. I eventually made so many changes to it that it made more sense to rewrite my own.

* Documentation: rdoc.info/projects/binarylogic/resourcelogic

Contextual Development

The idea behind contextual development is simple: an API should be a be a byproduct of good design. Meaning you should never have to explicitly build an API. It should, in essence, be an “accident”.

1. No need to namespace controllers when you have context

Your interface should not dictate the structure of your controllers. Instead, your controllers should represent a collection of resources that your interface can use (AKA an API). The problem is that rails does so much magic, and makes so many assumptions, that sometimes it distorts the basics behind the MVC pattern.

A good example is using Flex to build your interface. This allows you to go back to the basics behind RESTful development by forcing you to separate your interface from your application. A flex interface communicates with your application via XML. As a result, when you complete your application you also have a “production ready” API. You basically completed two projects in one.

That being said, why can’t we accomplish the same thing with an HTML interface? For one, an HTML interface isn’t as cleanly decoupled from the controllers as a Flex interface. For two, rails doesn’t give us all of the tools to properly accomplish this. Instead, people create work-arounds by namespacing controllers to represent context and/or scope (Ex: Admin::CommentsController). Why not have a single controller that is context aware? Hence the name “Contextual Development”. So instead of an Admin namespace, you can use the context to modify the interface / scope. Example:

class CommentsController < ApplicationController
  layout Proc.new { context == :admin ? "admin" : "application" }

  private
    # context is irrelevant when determining scope
    def scope
      current_user.admin? ? Comment : current_user.comments
    end
end

2. Single point of access for resources

Having a single controller is great, because it represents a single resource. This means that every request for that resource must pass through that single controller. Think about it, what is an API essentially? Controlled access to your database. You don’t go and create an entirely new model for every scope/context you use the model, do you? Why do the same for your API? Your API resources are the “models” for anyone using it, so it doesn’t make sense to have /comments and /admin/comments.

To bring it all home, all requests for a resource should pass through a single controller, in the same manner that all database activity for a table must pass through a single model. You can feel confident adding controller specific logic to that resource without having to worry about duplicating it across multiple controllers. A very simple example: storing the user’s IP address with a record.

3. Relative URL and path methods

Another big problem with using the same controller in various contexts is the need to specify relative paths instead of absolute paths. When you specify resources in your routes you get all kinds of useful absolute path methods, but where are the relative ones? Let’s say you have the following paths:

  1. /articles

  2. /admin/articles

Articles have many comments. What if you want to link to that article’s comments? Do you use article_comments_path or admin_article_comments_path? You could use the context method described above to determine this, but this will get messy and annoying very fast. Instead why not use child_collection_path(:comments)? The paths are relative based on a tree structure. So you also get parent and sibling paths. Now you can easily nest resources without having to worry about linking to them. See the documentation for more details on the various URL and path methods that are available to you.

Install and use

1. Install the gem

Install the gem / plugin (recommended)

$ sudo gem install resourcelogic

Now add the gem dependency in your config:

# config/environment.rb
config.gem "resourcelogic"

Or you install this as a plugin (for older versions of rails)

script/plugin install git://github.com/binarylogic/resourcelogic.git

2. Create your ResourceController

script/generate controller resource

Your ResourceController should look something like:

class ResourceController < ApplicationController
  acts_as_resource
end

Now all of your controllers that are “resources” can extend this controller. Why do this? So you can set your default behavior for resources in one spot. This idea what brought over from the resource_controller plugin. The DSL resource_controller came up with is pretty cool:

class ResourceController < ApplicationController
  acts_as_resource

  create.flash { # code to evaluate to create the flash message for a successful create }
  create.before { # code you want to execute before the create action }
  create.wants.js { # code you want to execute in the wants.js for a successful create }
  create.failure.flash { # code to evaluate to create the flash message for an unsuccessful create }
  create.failure.js { # code you want to execute in the wants.js for an unsuccessful create }
  # etc...See Resourcelogic::ActionOptions and Resourcelogic::FailableActionOptions for more details
end

All of these are overrideable, meaning your subclasses can change behavior in a granular manner, and preserve the defaults where necessary.

3. Make sure you don’t namespace your controllers

Instead of namespacing your controllers, give them context. For example, let’s say you you have /commments and /admin/comments. This controller has 2 contexts: root and admin. So your routes should look something like:

map.with_options(:path_prefix => "admin", :name_prefix => "admin_") do |admin|
  admin.resource :comments
end
map.resources :comments

Then in your controller use the context method to make adjustments:

class CommentsController < ResourceController
  layout Proc.new { context == :admin ? "admin" : "application" }
end

You also have the same context method in your views. Lastly, if you feel your views are getting cluttered by trying to determine what context you are in, you can use the namespace_views_by_context option (See Resourcelogic::Context::Config for more info). This will change your default view path to a context subfolder. Ex:

/comments
  /admin
  /root
  any other contexts..

See the Feature Highlights section below for more options, and the documentation for a complete list.

Feature highlights

I don’t want to repeat what is already in the documentation, but there are a lot of really nice configuration and utility methods. Here are just a few:

Class level methods

belongs_to :relationship_name   # will check to see if the resource is being scoped by a parent and give you some nifty methods for this (see below). You can call this multiple times. Just like ActiveRecord.
contextual_views true           # will split up your views into subfolders: comments/context1, comments/context2, and will change your default view path to the respective folder

Instance level methods

Lets pretend we are dealing with a products resource that belongs to a category.

context                                 # the name of the context you are in

object                                  # current product object, if any
collection                              # current collection of products
parent                                  # current category object, if any

Now you have all of the “relative routes” to help you easily nest resources and use them in different contexts:

object_path                             # /products/:id
edit_object_path                        # /products/:id/edit
new_object_path                         # /products/new
collection_path                         # /products

parent_path                             # /categories/:parent_id
edit_parent_path                        # /categories/:parent_id/edit
parent_collection_path                  # /categories
new_parent_path                         # /categories/new

sibling_path(sibling)                   # /sibling_name/:id
edit_sibling_path(sibling)              # /sibling_name/:id/edit
new_sibling_path(:sibling_name)         # /sibling_name/new
sibling_collection_path(:sibling_name)  # /sibling_name

child_path(child)                       # /products/:product_id/child_name/:id
edit_child_path(child)                  # /products/:product_id/child_name/:id/edit
new_child_path(:child_name)             # /products/:product_id/child_name/new
child_collection_path(:child_name)      # /products/:product_id/child_name

Notice you have the edit_* paths. The above paths are implemented in a very flexible manner. So you are not limited them, you can call your custom actions too:

map.resources :products, :member => [:approve], :collection => [:approve_all]
approve_object_path                     # /products/:id/approve
approve_all_collection_path             # /products/approve

The above example is probably not the best one, but you get the point.

Lastly, all of the above can end with _url instead of _path. See docs for a complete list of available methods.

Copyright © 2008 Ben Johnson of Binary Logic, released under the MIT license