Skip to content

Instantly share code, notes, and snippets.

@timruffles
Last active August 29, 2015 14:10
Show Gist options
  • Save timruffles/d9b70cd609529e8e26f5 to your computer and use it in GitHub Desktop.
Save timruffles/d9b70cd609529e8e26f5 to your computer and use it in GitHub Desktop.
transforms vs ifs

I was changing the behaviour of this controller, and wondered if there was some way to make it less branchy and more self-documenenting.

I remembered an idea of Dave Thomas's - thinking about programs as series of transforms - and tried to apply it.

Which do you prefer?

class OauthController < ApplicationController
# creates a new external service every time, and removes old, to ensure
# we capture any updated information from user trusting us with more
def create
existing_service = ExternalService.find_with_oauth(auth)
user = nil
if signed_in?
# a new or updated oauth for the current user
user = current_user
else
# a signup, or login
user = if existing_service
existing_service.user
else
User.create_with_oauth(auth)
end
sign_in(user)
end
ExternalService.create_or_update_with_oauth(auth, user, existing_service)
redirect_to home_url
end
private
def auth
request.env['omniauth.auth']
end
end
class OauthController < ApplicationController
# creates a new external service every time, and removes old, to ensure
# we capture any updated information from user trusting us with more
def create
existing_service = ExternalService.find_with_oauth(auth)
user = case authorisation_state(existing_service)
when :logged_in
current_user
when :login
existing_service.user
when :signup
User.create_with_oauth(auth)
end
ExternalService.create_or_update_with_oauth(auth, user, existing_service)
sign_in(user)
redirect_to home_url
end
private
def authorisation_state existing_service
if signed_in?
:logged_in
else
existing_service ? :login : :signup
end
end
def auth
request.env['omniauth.auth']
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment