socialforge/app/services/watches_service.rb

62 lines
2.1 KiB
Ruby
Raw Normal View History

2015-03-05 09:26:13 +08:00
#coding=utf-8
2014-12-10 16:23:56 +08:00
class WatchesService
2014-12-10 14:33:05 +08:00
def watch params
@current_user = User.find(params[:current_user_id])
2015-03-05 09:26:13 +08:00
if params[:object_type] == 'user' && params[:current_user_id] == params[:object_id]
raise '不能关注自己!'
end
2014-12-10 14:33:05 +08:00
@watchables = find_watchables params
2015-03-05 09:26:13 +08:00
2014-12-10 14:33:05 +08:00
if @watchables.nil?
raise '404'
2014-12-10 14:33:05 +08:00
end
set_watcher(@watchables, @current_user, true)
2014-12-10 14:33:05 +08:00
end
def unwatch params
@current_user = User.find(params[:current_user_id])
@watchables = find_watchables params
if @watchables.nil?
raise '404'
end
set_watcher(@watchables, @current_user, false)
2014-12-10 14:33:05 +08:00
end
def find_watchables params
#根据参数获取关注对象的类型user、project
klass = Object.const_get(params[:object_type].camelcase) rescue nil
#判断获取的对象类型能否响应watched_by方法
if klass && klass.respond_to?('watched_by')
@watchables = klass.find_all_by_id(Array.wrap(params[:object_id]))
raise Unauthorized if @watchables.any? {|w| w.respond_to?(:visible?) && !w.visible?}
end
@watchables.present? ? @watchables : nil
end
def set_watcher(watchables, user, watching)
watchables.each do |watchable|
watchable.set_watcher(user, watching)
# @user = watchable # added by william
if watching
# 修改 user和project的状态
if watchable.instance_of?(User)
#写user_statuses表
UserStatus.find_by_user_id(watchable.id).update_watchers_count(1)
elsif watchable.instance_of?(Project)
#写project_statuese表
ProjectStatus.find_by_project_id(watchable.id).update_watchers_count(1)
end
else
# 修改 user和project的状态
if watchable.instance_of?(User)
#写user_statuses表
UserStatus.find_by_user_id(watchable.id).update_watchers_count(-1)
elsif watchable.instance_of?(Project)
#写project_statuese表 :project_status
ProjectStatus.find_by_project_id(watchable.id).update_watchers_count(-1)
end
end
end
watchables
2014-12-10 14:33:05 +08:00
end
end