Reputation: 13140
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
Upvotes: 0
Views: 2711
Reputation: 5661
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
Upvotes: 4