Faye and changing models in your rails app
-
11-12-2019 - |
Question
i'm using FAYE and rails application and the only thing tha annoys me very much is that i cant create or change models on message recieved.
It seems like it should be something like https://github.com/jamesotron/faye-rails but it s kinda hassle.
Is there any way to update models through extensions? maybe something like this:
require 'faye'
require './app/models/message.rb'
Faye::WebSocket.load_adapter('thin')
require File.expand_path('../config/initializers/faye_token.rb', __FILE__)
class MsgMonitor
def incoming(message, callback)
Message.create(:name=>message.to_s)
callback.call(message)
end
end
faye_server = Faye::RackAdapter.new(:mount => '/faye', :timeout => 45)
faye_server.add_extension(ServerAuth.new)
faye_server.add_extension(MsgMonitor.new)
run faye_server
but it gives an error. So defiitely it should somehow load the whole rails environment(and that is actually needed).
Any help will be highly appreciated....
PS Tried to subsribe to channel using Google Group article http://groups.google.com/group/faye-users/browse_thread/thread/620ee6440422687a?pli=1 but still cant get it to work. It publishes but not getting back by subscription.
Solution
What has been working for me is to have the faye server only responsible for passing and validating messages. If that is successful I save them into redis the same way that resque does so it can finish the processing.
The benefits are that long running tasks don't slow down your faye connections, and you can always add more workers if you need further processing.
at the top of my first extension's incoming method I create a new em-redis connection
$redis ||= EM::Hiredis.connect @options[:redis]
then if it passes my tests I store it in redis in the format that resque uses.
m = {'class' => "Message", 'args' => ['handle_message', {name: message.to_s}.to_json]}
$redis.rpush("resque:queue:faye", m.to_json )
$redis.sadd("resque:queues","faye")
for transmitting out of my rails app to users I use the following code in a script/faye_worker
https://github.com/SponsorPay/em-resque#in-a-rails-3-app-as-a-gem
I wrap the above with EM.synchrony so that I can init faye before the worker
to send messages out of your model just send it to the async resque queue.