Robin Winton
Robin Winton

Reputation: 601

How to use the same method in 2 controllers?

I have a Rails 2 app with an API. I versioned and optimised the controllers but there are duplicate methods. The goal is to have the common information in only one place. So I explored the following options:

  1. redirect from routes the non-API controller, but each controller needs it's specific hooks

  2. module inclusion. This is my favorite but there are like quite a lot of errors thrown out and very limited time to fix things up.

  3. eval. Put all the code in one file and eval it in both places. Done this, it works but I am not pleased by this workaround.

What would be the best to go about this?

Upvotes: 1

Views: 1013

Answers (1)

railsdog
railsdog

Reputation: 1501

Might be some typos lurking in here but:

class GenericController < ApplicationController
  def index
    @objects = params[:controller].singularize.camelcase.constantize.all()
  end

  def show
    @object = params[:controller].singularize.camelcase.constantize.find(params[:id])
  end

  def new
    @object = params[:controller].singularize.camelcase.constantize.new
  end

  def edit
    @object = params[:controller].singularize.camelcase.constantize.find(params[:id])
  end

  def create
    model = params[:controller].singularize.downcase
    @object = params[:controller].singularize.camelcase.constantize.new(params[model])
    if @object.save
      redirect_to '/'+params[:controller]
    else
      render :action => 'new'
    end
  end

  def update
    model = params[:controller].singularize.downcase
    @object = params[:controller].singularize.camelcase.constantize.find(params[:id])
    if @object.update_attributes(params[model])
      redirect_to :controller => params[:controller], :action => 'index'
    else
      render :action => 'edit'
    end
  end

  def destroy
    if @object = params[:controller].singularize.camelcase.constantize.find(params[:id])
      @object.destroy
    end
    redirect_to :controller => params[:controller], :action => 'index'
  end

end

Specific controllers can override those implementations as needed, but:

class ProjectsController < GenericController
  # done!
end

class ScenariosController < GenericController
  # done!
end

Upvotes: 1

Related Questions