Skip to content

Instantly share code, notes, and snippets.

@ralphking
Created February 10, 2015 10:48
Show Gist options
  • Save ralphking/b86edbaefad1794e4385 to your computer and use it in GitHub Desktop.
Save ralphking/b86edbaefad1794e4385 to your computer and use it in GitHub Desktop.
Persisting guests users in devise.
# use this if you are using cancan/cancancan gem for authoriazation. This passes your new current_or_guest_user method to cancan rather
# than the usual devise current_user method
def current_ability
@current_ability ||= Ability.new(current_or_guest_user)
end
module AuthorizationHelper
# if user is logged in, return current_user, else return guest_user
def current_or_guest_user
if current_user
if cookies.signed[:guest_user_id]
logging_in
guest_user.delete
cookies.delete :guest_user_id
end
current_user
else
guest_user
end
end
# find guest_user object associated with the current session,
# creating one as needed
def guest_user
# Cache the value the first time it's gotten.
@cached_guest_user ||=
User.find_by!(id: (cookies.permanent.signed[:guest_user_id] ||= create_guest_user.id))
# if cookies.signed[:guest_user_email] invalid
rescue ActiveRecord::RecordNotFound #
cookies.delete :guest_user_id
guest_user
end
private
# called (once) when the user logs in, insert any code your application needs
# to hand off from guest_user to current_user.
def logging_in
# For example:
# guest_bookings = guest_user.bookings.all
# guest_bookings.each do |booking|
# booking.user_id = current_user.id
# booking.save!
# end
end
# creates guest user by adding a record to the DB
# with a guest name and email
def create_guest_user
# pass client into the user job
c = Client.new(:firstname => "guest")
c.build_user(:email => "guest_#{Time.now.to_i}#{rand(99)}@example.com")
c.save!(:validate => false)
c
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment