acts_as_polymorphic_controller

Description

acts_as_polymorphic_controller is a bit of code written to assist me with a Rails3 project. I became increasingly tired of handling polymorphism by using if/case statements:

if params[:user_id]
  @obj = User.find(params[:user_id])
elsif params[:group_id]
  @obj = Group.find(params[:group_id])
elsif params[:whatever_id]
  @obj = Whatever.find(params[:whatever_id])
end

This gem aims to alleviate that annoyance.

Features

Examples

In ApplicationController.rb

include ActsAsPolymorphicController

In some controller file, such as: BlogPostsController.rb

class BlogPostsController < ApplicationController
  acts_as_polymorphic_controller

  # These are the models that have_many BlogPosts, :as 
  aapc_resources :user, :group, :event

  def index
    @object = aapc_parent_object
  end 
end

In this example, each of the following URLs would return the appropriate instace into the @object variable:

/users/5/blog_posts (User :id => 5) /groups/3/blog_posts (Group :id => 3) /events/12/blog_posts (Event :id => 12)

Requirements

Install

$ gem install acts_as_polymorphic_controller

Copyright © 2010 rob

See LICENSE.txt for details.