Skip to content

Instantly share code, notes, and snippets.

@Olefine
Created July 9, 2013 10:55
Show Gist options
  • Save Olefine/5956499 to your computer and use it in GitHub Desktop.
Save Olefine/5956499 to your computer and use it in GitHub Desktop.
user model
class User < ActiveRecord::Base
#default_scope where(:banned => false)
scope :unbanned, where(:banned => false)
include ChooseCity
rolify
acts_as_voter
has_karma(:questions, :as => :submitter, :weight => 0.5)
mount_uploader :avatar, AvatarUploader
devise :invitable, :database_authenticatable, :registerable, #:confirmable,
:recoverable, :rememberable, #, :validatable#, :trackable #
:omniauthable
attr_accessor :read # user's agreement
attr_accessible :email, :password, :remember_me, :vk, :fb, :tw, :mailru,
:type_user, :provider, :uid, :avatar, :profileable_id, :profileable_type, :read
attr_accessible :email, :password, :remember_me, :vk, :fb, :tw, :mailru,
:type_user, :provider, :uid, :avatar, :banned, :read, :admin_role_ids, :as => :admin
validates :read, :presence => true, :on => :create
validate :password_complexity
validates :email, :presence => true, :uniqueness => true
validates :profileable_id, :presence => true
acts_as_commentable
DEPTH = 2
belongs_to :profileable, :polymorphic => true, :dependent => :destroy
has_many :videos, :class_name => "MediaContent", :as => :multimedia, :conditions => ["media_contents.video = ?", true]
has_many :audios, :class_name => "MediaContent", :as => :multimedia, :conditions => ["media_contents.video = ?", false]
has_many :likes, :as => :likeable
has_many :complaints, :as => :pretension, :dependent => :destroy
has_many :invitations, :class_name => 'User', :as => :invited_by
has_many :friendships
has_many :friends, :through => :friendships, :source => :friend, :conditions => "friendships.status = 'accepted'"
has_many :friendships_awaiting_acceptance, :conditions => "friendships.status = 'requested'", :class_name => 'Friendship', :foreign_key => :friend_id
has_and_belongs_to_many :message_rooms
has_many :messages
has_many :group_messages, foreign_key: :creator_id
has_many :sent_messages, :class_name => "Message"
has_many :received_messages, :class_name => "Message", :foreign_key => :recipient_id
has_many :unread_messages, :class_name => "Message", :foreign_key => :recipient_id, :conditions => "messages.read = false"
has_many :albums, :as => :resource
has_many :photos, :through => :albums
has_many :posts, :as => :journal, :dependent => :destroy
has_and_belongs_to_many :communities
has_many :admin_roles, :source => :role, :through => :users_roles, :conditions => {:roles => {:resource_type => nil, :resource_id => nil, :name => [:admin, :moderator]}}
has_many :users_roles
scope :last_users, ->(count) { order("id DESC").limit(count) }
def custom_remove_role name, resource
delete_role = roles.where(resource_type: resource.class.to_s,
resource_id: resource.id,
name: name).first
delete_users_roles = delete_role.users_roles.where(user_id: id).first
delete_users_roles.destroy
end
def self.find_for_facebook_oauth(auth, signed_in_resource=nil)
User.where(:provider => auth.provider, :uid => auth.uid).first
end
def self.find_for_vkontakte_oauth(auth, signed_in_resource=nil)
User.where(:provider => auth.provider, :uid => auth.uid).first
end
def self.find_for_mailru_oauth(auth, signed_in_resource=nil)
User.where(:provider => auth.provider, :uid => auth.uid).first
end
def self.new_with_session(params, session)
super.tap do |user|
if data = session["devise.omniauth_data"] && session["devise.omniauth_data"]["extra"]["raw_info"]
user.email = data["email"] if user.email.blank?
user.name = data["first_name"] if user.name.blank?
user.surname = data["last_name"] if user.surname.blank?
user.login = data["username"] || data["screen_name"] || data["nick"] if user.login.blank?
user.provider = session["devise.omniauth_data"]["provider"]
user.uid = session["devise.omniauth_data"]["uid"]
end
end
end
def name
self.client.try(:firstname)||self.firm.try(:name)
end
def client
return self.profileable if self.profileable_type == 'Client'
end
def firm
return self.profileable if self.profileable_type == 'Firm'
end
def is?(user)
self.id == user.id
end
#Дружба
def friends?(friend)
friendship = self.friendship_for(friend)
!!(friendship && friendship.accepted?)
end
def accept_friendship_with(friend)
if (pendent = self.friendship_for(friend)).pending?
requested = friend.friendship_for(self)
ActiveRecord::Base.transaction do
pendent.accept!
requested.accept! unless requested.accepted?
end
# else
# # raise YouCanNotJudgeARequestFriendshipError
end
end
def deny_friendship_with(friend)
if (pendent = self.friendship_for(friend)).pending?
ActiveRecord::Base.transaction do
[self.friendship_for(friend), friend.friendship_for(self)].compact.each do |friendship|
friendship.destroy if friendship
end
end
# else
# raise YouCanNotJudgeARequestFriendshipError
end
end
def remove_friendship_with(friend)
ActiveRecord::Base.transaction do
[self.friendship_for(friend), friend.friendship_for(self)].compact.each do |friendship|
friendship.destroy if friendship
end
end
end
def be_friends_with(friend)
# no user object
return nil, Friendship::STATUS_FRIEND_IS_REQUIRED unless friend
# should not create friendship if user is trying to add himself
return nil, Friendship::STATUS_IS_YOU if self.is?(friend)
# should not create friendship if users are already friends
return nil, Friendship::STATUS_ALREADY_FRIENDS if self.friends?(friend)
# retrieve the friendship request
friendship = self.friendship_for(friend)
# let's check if user has already a friendship request or have removed
request = friend.friendship_for(self)
# friendship has already been requested
return nil, Friendship::STATUS_ALREADY_REQUESTED if friendship && friendship.requested?
# friendship is pending so accept it
if friendship && friendship.pending?
ActiveRecord::Base.transaction do
friendship.accept!
request.accept!
end
return friendship, Friendship::STATUS_FRIENDSHIP_ACCEPTED
end
ActiveRecord::Base.transaction do
# we didn't find a friendship, so let's create one!
friendship = self.friendships.create(:friend_id => friend.id, :status => Friendship::FRIENDSHIP_REQUESTED, :requested_at => Time.now)
# we didn't find a friendship request, so let's create it!
request = friend.friendships.create(:friend_id => id, :status => Friendship::FRIENDSHIP_PENDING, :requested_at => Time.now)
end
return friendship, Friendship::STATUS_REQUESTED
end
def friendship_for(friend)
self.friendships.first :conditions => {:friend_id => friend.id}
end
def grouped_friends(friends=self.friends)
all = friends.map(&:profileable).group_by{|f| f.class.name}
return all['Firm'], all['Client']
end
#Личные сообщения
def send_message(recipient, body, message_room = nil)
self.transaction do
if message_room.nil? && general_room(recipient).nil?
message_room = MessageRoom.create
self.message_rooms << message_room
recipient.message_rooms << message_room
message_room_id = message_room.id
else
message_room_id = general_room(recipient)
end
self.messages.new(:message_room_id => message_room_id, :recipient_id => recipient.id, :body => body)
end
end
def general_room(recipient)
room_ids = (self.message_room_ids & recipient.message_room_ids)
room_ids.first
end
def my_message?(message)
self.id == message.user_id
end
def reply(message)
if my_message?(message)
message.self_reply
else
message.reply
end
end
def owner?(user)
self.id == user.id
end
def comment_threads
Comment.find_comments_for_commentable(profileable_type, profileable_id)
end
def root_object
self
end
#########################################################################
def can_edit?(user)
true
end
#Пользователь который пригласил
def invited_couple
User.find(self.couple_id)
end
def self.search_couple(exclude_obj, search_string, limit = 10)
q = search_string.to_s.gsub(/\\/, '\\\\\\\\').gsub(/%/, '\%').gsub(/_/, '\_')
self.no_couple.where("id <> ? and (name like '%#{q}%' or surname like '%#{q}%') and gender <> ?", exclude_obj.id, exclude_obj.gender).limit(limit)
end
private
def password_complexity
if password.present? and not password.match(/^[0-9A-Za-z#\$-%]{6,}$/)
errors.add :password, "Должен содержать не менее 6 смиволов, может содержать A-Za-z,0-9,(#$-%)"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment