How does the `new` keyword work in this Ruby method definition?
refactoring, ruby, ruby-on-rails
Solution
the classname is implicit in self methods. The code could have be written like:
def self.from_email(email)
PasswordReset.new User.find_by_email(email)
end
To answer the 2nd half of your question, `attr_reader` defines an instance variable and a reader method (aka getter method if you're coming from java or c#). Putting it all together, you could have written it as :
class PasswordReset
def user
@user
end
def self.from_email(email)
PasswordReset.new User.find_by_email(email)
end
def self.from_token(token)
PasswordReset.new User.find_by_password_reset_token!(token)
end
...
end
This is assuming PasswordReset#initialize takes a User as a parameter, and sets @user accordingly
Problem
Railscasts put out a great episode on refactoring. One method is to move complex controller logic into service objects instead of pushing it down the model. In one service object, the following code is used: ``` class PasswordReset attr_reader :user def self.from_email(email) new User.find_by_email(email) end def self.from_token(token) new User.find_by_password_reset_token!(token) end ... end ``` What does the `new` key word serve in both method bodies? `new User.find_by_`. How is that different from `User.find_by_` ? Here's the calling code: ``` def create # controller password_reset = PasswordReset.from_email(params[:email]) if password_reset.user password_reset.send_email redirect_to root_url, notice: "Email sent with password reset instructions." else redirect_to new_password_reset_url, alert: "Email address does not match a user account." end end ``` Also, why the `attr_reader :user` needed?