Last active
May 26, 2020 10:15
-
-
Save pixeltrix/b408f9be9f7aaaebc4f2c7d6088cd039 to your computer and use it in GitHub Desktop.
Example of a 'service' object
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ActivationsController < ApplicationController | |
respond_to :json | |
def create | |
new_password = params[:user] && params[:user][:password] | |
token = params[:confirmation_token] | |
if !new_password | |
render_errors({"password"=>["can't be blank"]}.to_json) | |
elsif (@user = User.for_confirmation_token(token)) | |
if @user.try(:suspended?) | |
render_unauthorized @user.inactive_message | |
else | |
setter = PasswordSetter.new(@user) | |
setter.set_password new_password, self | |
end | |
else | |
render_unauthorized | |
end | |
end | |
def render_success | |
@user.confirm! | |
super | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class PasswordSetter | |
def initialize user | |
@user = user | |
end | |
def set_password password, responder | |
@user.password = password | |
if @user.valid? | |
@user.save! | |
responder.render_success | |
else | |
errors = @user.errors.messages.to_json | |
responder.render_errors errors | |
end | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class UsersController < ApplicationController | |
respond_to :json | |
def update | |
new_password = params[:user] && params[:user][:password] | |
token = params[:authentication_token] | |
if !new_password | |
render_errors({"password"=>["can't be blank"]}.to_json) | |
elsif (user = User.for_authentication_token(token)) | |
if user.suspended? | |
render_forbidden user.inactive_message | |
else | |
setter = PasswordSetter.new(user) | |
setter.set_password new_password, self | |
end | |
else | |
render_unauthorized | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment