2014-08-01 12:07:16 +02:00
|
|
|
class User < ActiveRecord::Base
|
|
|
|
# Include default devise modules. Others available are:
|
|
|
|
# :confirmable, :lockable, :timeoutable and :omniauthable
|
|
|
|
devise :database_authenticatable, :registerable,
|
2014-08-01 15:27:08 +02:00
|
|
|
:recoverable, :rememberable, :trackable,
|
|
|
|
:validatable, :authentication_keys => [:login]
|
|
|
|
|
|
|
|
# attr_accessor :login
|
|
|
|
|
2014-10-28 06:36:38 +01:00
|
|
|
has_many :questions, dependent: :destroy
|
|
|
|
has_many :answers, dependent: :destroy
|
|
|
|
has_many :comments, dependent: :destroy
|
2014-11-10 23:45:36 +01:00
|
|
|
has_many :inboxes, dependent: :destroy
|
2014-11-30 14:43:35 +01:00
|
|
|
has_many :active_relationships, class_name: 'Relationship',
|
|
|
|
foreign_key: 'source_id',
|
|
|
|
dependent: :destroy
|
|
|
|
has_many :passive_relationships, class_name: 'Relationship',
|
|
|
|
foreign_key: 'target_id',
|
|
|
|
dependent: :destroy
|
|
|
|
has_many :friends, through: :active_relationships, source: :target
|
|
|
|
has_many :followers, through: :passive_relationships, source: :source
|
|
|
|
|
2014-08-01 15:27:08 +02:00
|
|
|
SCREEN_NAME_REGEX = /\A[a-zA-Z0-9_]{1,16}\z/
|
|
|
|
|
|
|
|
validates :screen_name, presence: true, format: { with: SCREEN_NAME_REGEX }, uniqueness: { case_sensitive: false }
|
2014-11-11 20:20:00 +01:00
|
|
|
|
|
|
|
|
|
|
|
|
2014-08-01 15:27:08 +02:00
|
|
|
def login=(login)
|
|
|
|
@login = login
|
|
|
|
end
|
|
|
|
|
|
|
|
def login
|
|
|
|
@login || self.screen_name || self.email
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.find_first_by_auth_conditions(warden_conditions)
|
|
|
|
conditions = warden_conditions.dup
|
|
|
|
if login = conditions.delete(:login)
|
|
|
|
where(conditions).where(["lower(screen_name) = :value OR lower(email) = :value", { :value => login.downcase }]).first
|
|
|
|
else
|
|
|
|
where(conditions).first
|
|
|
|
end
|
|
|
|
end
|
2014-11-30 15:13:17 +01:00
|
|
|
|
|
|
|
# follows an user.
|
|
|
|
def follow(target_user)
|
|
|
|
active_relationships.create(target: target_user)
|
|
|
|
|
|
|
|
# increment counts
|
|
|
|
increment! :friend_count
|
|
|
|
target_user.increment! :follower_count
|
|
|
|
end
|
|
|
|
|
|
|
|
def unfollow(target_user)
|
|
|
|
active_relationships.find_by(target: target_user).destroy
|
|
|
|
|
|
|
|
# decrement counts
|
|
|
|
decrement! :friend_count
|
|
|
|
target_user.decrement! :follower_count
|
|
|
|
end
|
|
|
|
|
|
|
|
# @return [Boolean] true if +current_user+ is following +target_user+
|
|
|
|
def following?(target_user)
|
|
|
|
friends.include? target_user
|
|
|
|
end
|
2014-08-01 12:07:16 +02:00
|
|
|
end
|