`

基于redis的消息推送+messengerjs-rails

阅读更多
添加redis纪录回调:
class Notification < ApplicationRecord
  def read!
    self.read_at = Time.now
    self.save
  end

  belongs_to :operator, :class_name => "Employee", :foreign_key => "operator_id"
  default_scope ->{where("read_at is null")}

  before_create :add_redis_message

  def add_redis_message
    message_hash = Redis::HashKey.new("employee_#{self.employee_id}")
    message_hash["#{self.link}"] = "#{self.msg}"
  end

end


class Admin::NotificationsController < Admin::BaseController
  include ExemptedFromLogging
  
  def index
    employee_id = current_employee.id
    redis = Redis::HashKey.new("employee_#{employee_id}")
    if redis.blank?
      render :json=> nil
    else
      render :json=> redis.to_json
    end
  end

  def show_massage
    employee_id = current_employee.id
    redis = Redis::HashKey.new("employee_#{employee_id}")
    redis.delete(params[:url])
    redirect_to params[:url]
  end

end


在aplication.js中添加:
//= require messenger
//= require messenger-theme-future

Messenger.options = {
  extraClasses: 'messenger-fixed messenger-on-bottom messenger-on-right',
  theme: 'block',
  messageDefaults: {
    showCloseButton: true,
    hideAfter: 0
  }
}

var refreshMessages =  (function(){
  return function(){
    $.get('/admin/notifications', function(response){
      $.each(response, function() {
        var _this = this;
        var url = this.toString().split(",")[0]
        var value = this.toString().split(",")[1]
        var attr = { message: '[url=/admin/notifications/show_massage?url='+url+']' + value + '[/url]', type: 'info' ,id:value};
        Messenger().post(attr);
      });
    }, 'json');
  }
})();
var startRefreshMessages = function(){
  refreshMessages();
  setInterval(refreshMessages, 5 * 1000);
}



layout 中引入:

   <script type="text/javascript">
      <% if !Rails.env.development? %>
        startRefreshMessages();
      <% end %>
   </script>


gem requie

  gem "messengerjs-rails", "~> 1.4.1"
0
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics