views:

21

answers:

1

Hi!

I'm trying to refactor some code and move some of my before_filter's from the controller to a class.

Before:

class UsersController < ApplicationController
   before_filter :find_user

   def find_user
      @user = User.find(params[:id])
   end
end

...

After

class FindUserFilter
    def self.filter(controller)
        @user = User.find(params[:id])
    end
end

class UsersController < ApplicationController
   before_filter FindUserFilter
end

class GuestbookController < ApplicationController
   before_filter FindUserFilter
end

This results in an error because neither params[:id] nor @user is available/definable in the FindUserFilter-class.

Any idea how to fix this?

+1  A: 

Your code must be run within the @controller scope. One solution would be

class FindUserFilter
  def self.filter(controller)
    controller.instance_eval do
      @user = User.find(params[:id])
    end
  end
end
Simone Carletti
Worked like a charm. Thank you sir :-)
Mattias