Topic: Refactoring pointers

I'm going to have a crack at refactoring some redundant code I have in my controllers. I have the following three lines present in a number of methods that identifies a user from a browser environment variable and looks them up in my database's users table:

@kerberos = request.env["REMOTE_USER"]
username = ["kerberos LIKE ?", @kerberos]
@user = User.find(:first, :conditions => username)

How do I go about refactoring this into one method and calling that method in all the other methods that require this in my controller?

Re: Refactoring pointers

At least part of this code should go in the model. Whenever you're calling a find with conditions, move it to the model. For example:

# model (might want to rename some of this as I'm not sure what kerberos is)
def self.with_name(name)
  find(:first, :conditions => "kerberos LIKE ?", name])

# controller
@user = User.with_name(request.env["REMOTE_USER"])

You can then refactor it further by moving it into the application controller.

# application.rb
helper_method :current_user
def current_user
  @current_user ||= User.with_name(request.env["REMOTE_USER"])

And then you can call "current_user" in any controller or view. No need to set it as the @user instance variable anymore in each controller.

Again, I'm not sure exactly what you're doing here, so you may want to change the method names.

Railscasts - Free Ruby on Rails Screencasts