Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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