Skip to content

Instantly share code, notes, and snippets.

@timbeiko
Created July 11, 2015 19:39
Show Gist options
  • Save timbeiko/bd1a827f5f11f2790670 to your computer and use it in GitHub Desktop.
Save timbeiko/bd1a827f5f11f2790670 to your computer and use it in GitHub Desktop.
User slugs
# User.rb
class User <ActiveRecord::Base
before_save :generate_slug
# [...]
def self.from_omniauth(auth)
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.provider = auth.provider
user.uid = auth.uid
user.first_name = auth.info.first_name
user.last_name = auth.info.last_name
user.email = auth.info.email
if auth.provider == "facebook"
user.image = auth.info.image + "?type=large"
user.token = auth.credentials.token
user.expires_at = Time.at(auth.credentials.expires_at)
end
user.save!
end
# This is here so that the "provider" is not taken into account when seraching for users.
# This way, users from different providers will not have the same slug.
# But not it doesn't work with my 'sessions#new' action
# u = User.last
# u.generate_slug
# u.save!
# return User.where(provider: auth.provider, uid: auth.uid).first
end
def generate_slug
the_slug = to_slug(self.first_name.to_s + self.last_name.to_s)
object = User.find_by slug: the_slug
count = 2
while object && object !=self
the_slug = append_suffix(the_slug, count)
object = self.class.find_by slug: the_slug
count += 1
end
self.slug = the_slug.downcase
end
def append_suffix(str, count)
if str.split('-').last.to_i != 0
return str.split('-').slice(0...-1).join('-') + "-" + count.to_s
else
return str + "-" + count.to_s
end
end
def to_slug(name)
str = name.strip
str.gsub! /\s*[^A-Za-z0-9]\s*/, '-'
str.gsub! /-+/, '-'
str.gsub! /^-+|-+$/, ''
str.downcase
end
end
# Sessions_controller.rb
class SessionsController < ApplicationController
def new
end
def create
user = User.from_omniauth(env["omniauth.auth"])
session[:user_id] = user.id
if user
redirect_to user_path(current_user)
else
redirect_to :back
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment