mattSpell/hot-or-not

View on GitHub
app/models/user.rb

Summary

Maintainability
A
25 mins
Test Coverage
class User < ActiveRecord::Base
  has_many :viewed_homes
  has_many :homes, through: :viewed_homes
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable,
         :omniauthable, :omniauth_providers => [:facebook, :twitter]

  validates_presence_of :email
  validates_presence_of :password, on: :create
  validates_uniqueness_of :email

  def self.from_omniauth(auth)
    where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
      if auth.info.email
        user.email = auth.info.email
      else
        user.email = "random#{rand(9999)}@random.com"
      end
      user.password = Devise.friendly_token[0,20]
      user.name = auth.info.name
    end
  end

  def self.new_with_session(params, session)
    super.tap do |user|
      if data = session["devise.facebook_data"] && session["devise.facebook_data"]["extra"]["raw_info"]
        user.email = data["email"] if user.email.blank?
      end
    end
  end
end