Skip to content

Instantly share code, notes, and snippets.

@pixeltrix
Last active May 26, 2020 10:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pixeltrix/b408f9be9f7aaaebc4f2c7d6088cd039 to your computer and use it in GitHub Desktop.
Save pixeltrix/b408f9be9f7aaaebc4f2c7d6088cd039 to your computer and use it in GitHub Desktop.
Example of a 'service' object
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
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
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