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