0

I'm working with Rails 4.0 and I want to eliminate some duplicate lines but I don't know the implications doing this in Rails. As I understand an instance of a controller is created in every request 1.

class ResetController < ApplicationController
  def reset_password
    user = User.find_by_email(params[:email])
    if user
      ...
  end

  def reset_user_token
    user = User.find_by_email(params[:email])
    if user
      ...
  end
end

If I'm not using Rails, my idea is extract a private method using memoization and remove the duplicated lines:

private

def user
  @user ||= User.find_by_email(params[:email])
end

Is it a good idea do this in Rails controller? How do you improve this code? I have a similar problem in a lot of parts of the application.

Related:
- When to use memoization in Ruby on Rails
- Rails Best Practices: Use memoization

1
  • 2
    its perfectly fine in this context Commented Feb 11, 2014 at 12:09

1 Answer 1

4

This seems not to have much to do with memoization, since as you say yourself, a new instance is started between those requests, so nothing would be 'stored'.

Still removing those duplicates in your code is a good idea. The Rails way to do this in your case would be a before_filter:

class ResetController < ApplicationController
  before_filter :find_user

  protected
  def find_user
    @user = User.find_by_email(params[:email])
    # here you could add some exception handling and prevent execution of action if no user is found (assuming you want to do this)
  end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.