ruby-on-railsfayerackup

Update activerecords in faye event listeners


I am writing a rails app which requires to track users' status to see if they are available, busy or offline. I'm using the private_pub gem, which uses Faye underneath. When a user signs in he subscribes to a channel /user/[:user_id]. I want to update user's status to ONLINE when they subscribe using Faye's subscribe event listener. I added this code at the end of private_pub.ru file:

server = PrivatePub.faye_app

server.bind :subscribe do |client_id, channel|
  if /\/user\/*/.match(channel)
      m = /\/user\/(?<user_id>\d+)/.match(channel)
      user_id = m[:user_id]
  end
  user = User.find(user_id)
  user.status = 1 # 1 means online
end

run server

The problem is every time a user subscribes, thin server reports:

[ERROR] [Faye::RackAdapter] uninitialized constant User

I guess I need to require certain files to be able to use activerecords in the rackup file. But I don't know how.

Thanks for any help.


Solution

  • In our project we decide to use redis for similar case.

    Gemfile:

    gem 'redis-objects'
    

    Faye: use redis-rb for writing status

    require 'redis'
    Redis.current = Redis.new(:host => '127.0.0.1', :port => 6379)
    
    # init faye server
    ...
    
    server.bind(:subscribe) do |client_id, channel|
      if /\/user\/*/.match(channel)
        m = /\/user\/(?<user_id>\d+)/.match(channel)
        Redis.current.set("user:#{m[:user_id]}:online_status", "1")
      end
    end
    

    Rails: use redis-objects gem for reading it in User's model.

    class User < ActiveRecord::Base
      include Redis::Objects
      value :online_status
    end
    
    @user.online_status # returns "1" if channel is connected
    

    Hope this helps.