Created
September 9, 2011 10:10
-
-
Save loss-zz/1205886 to your computer and use it in GitHub Desktop.
notifications_all.rb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#-----数据库schema | |
#attachable 为虚拟属性,为兼容以后的私信notif之类的 | |
create_table :notifications do |t| | |
t.belongs_to :user | |
t.references :attachable, :polymorphic => true | |
t.text :content | |
t.timestamps | |
end | |
add_index :notifications, :user_id | |
add_index :notifications, [:attachable_id, :attachable_type] | |
#------end | |
class User < ActiveRecord::Base | |
include Redis::Objects | |
has_many :notifications | |
list :notifs #利用redis的list来存储未读notification标识 | |
def notifs_count | |
self.notifs.size | |
end | |
memoize :notifs_count | |
end | |
class NotificationsController < ApplicationController | |
before_filter :authenticate | |
before_filter :do_for_notif, :only => [:index] | |
private | |
def do_for_notif | |
current_user.notifs.clear #点击查看Notifications列表时候清空notifs | |
end | |
end | |
class TopicsController < ApplicationController | |
before_filter :find_topic, :except => [:index,:new] | |
before_filter :do_for_notif, :only => [:show] | |
private | |
def find_topic | |
@topic = Topic.find(params[:id]) | |
end | |
def do_for_notif | |
if signed_in? | |
current_user.notifs.delete("Topic::#{@topic.id}") #清除 notif | |
end | |
end | |
end | |
#利用Resque异步处理Notif | |
class TopicNotif | |
@queue = :notif_serve | |
def self.perform(user_id, topic_id, text) | |
usernames = extract_mentioned_screen_names(text).uniq | |
usernames.each do |username| | |
user = User.where(:name=>username).first | |
if user && user.id != user_id | |
content = "" #这里处理需要显示的提示文字 | |
user.notifications.build(:attachable_id=>topic_id, :attachable_type=>'Topic', :content=>content).save | |
user.notifs << "Topic::#{topic_id}" | |
end | |
end | |
end | |
end | |
class Topic < ActiveRecord::Base | |
after_create :async_for_notif | |
def async_for_notif | |
Resque.enqueue(TopicNotif, self.user_id, self.id, self.title+self.body) | |
end | |
end | |
class Post < ActiveRecord::Base | |
after_create :async_for_notif | |
def async_for_notif | |
Resque.enqueue(TopicNotif, self.user_id, self.topic_id, self.body) unless self.major | |
end | |
end | |
#views | |
<%= current_user.notifs_count > 200 ? '200+' : current_user.notifs_count %> 条提醒 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment