Ruby on Rails Friday, March 30, 2012



On Thu, Mar 29, 2012 at 7:28 PM, wbsurfver@yahoo.com <wbsurfver@gmail.com> wrote:
Your post has been very helpful, I tried something like what you
posted, but it didn't
quite make sense to me.

 If you look at what I have currently below, I have to have this
sleep(30) at the bottom which is not optimal.
a join on the thread doesn't work.

 I also tried run_block() instead of run() with no luck.

 I guess if I do everything inside of a EM that doesn't take too long,
it wouldn't matter, but I am trying to get an idea of
how this sort of thing should work

#########################


require 'eventmachine'

require 'faye'



client = Faye::Client.new('http://localhost:9292/faye')

thr = nil

if !EM.reactor_running?
   thr = Thread.new do
     EM.run do

       puts 'in ev machine'
       client.subscribe('/messages/public') do |message|
         puts message.inspect
       end

       puts '1'

       client.publish('/messages/public', 'username' => 'Joe',
                     'msg' => "hey there againzoggle")
       sleep 10
       puts '2'

       client.publish('/messages/public', 'username' => 'Joe',
                     'msg' => "hey there again")
       puts 'end of ev machine block'
     end
   end

 end

puts 'wait for running'
sleep 0.1 until EM.reactor_running?

sleep 30

puts 'end of client'

Ok, Rails is a single threaded application, once you start event machine inside the application flow, control is lost until a event triggers a return somehow. 
Do not put your code inside the EM block.

This is how i do it


class CommBridge
  
  def self.set_connection
    ensure_reactor_running
    @@client ||= self.set
    @@client
  end

private

   def self.set
     client =   Faye::Client.new("http://localhost:9292/faye", {timeout: 20})
     client.add_extension(ClientAuth.new) 
     return client
   end

  def self.ensure_reactor_running 
        Thread.new { EM.run } unless EM.reactor_running? 
        sleep 0.1 until EM.reactor_running? 
  end
  
  
  
end

class ClientAuth
  def outgoing(message, callback)
    if message['channel'] !~ %r{^/meta/}
     message['ext'] ||= {}
        message['ext']['authToken'] = "#{FAYE_TOKEN}"
  end
  callback.call(message)
  end
end

This calls takes care of creating a client fot he rails server.

Then anywhere in your app

client = CommBridge.set_connection
client.publish("/user/#{channel}",msg.to_json)



 

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

No comments:

Post a Comment