Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Faye

 Faye

Faye, czyli łatwe pubsub z websockets

Grzesiek Kolodziejczyk

October 20, 2011
Tweet

More Decks by Grzesiek Kolodziejczyk

Other Decks in Programming

Transcript

  1. faye wiadomości pub/sub serwer: node.js / ruby (rack) backend: ram

    / redis klient: ruby / js fallback do long-polling
  2. 1 # Run with: rackup faye.ru -s thin -E production

    2 require "yaml" 3 require "faye" 4 begin 5 require "private_pub" 6 rescue LoadError 7 require "bundler/setup" 8 require "private_pub" 9 end 10 11 PrivatePub.load_config("config/private_pub.yml", ENV["RAILS_ENV"] || "development") 12 run Faye::RackAdapter.new(:mount => "/faye", :timeout => 45, :extensions => [PrivatePub.faye_extension]) faye.ru
  3. 1 development: 2 server: "http://localhost:9292/faye" 3 secret_token: "secret" 4 test:

    5 server: "http://localhost:9292/faye" 6 secret_token: "secret" 7 production: 8 server: "http://liveblogs.code-fu.pl:9292/faye" 9 secret_token: "sekret ;)" config/private_pub.yml
  4. 1 class Stream 2 include Mongoid::Document 3 include PrivatePub::ViewHelpers 4

    5 belongs_to :user 6 embeds_many :messages 7 ... 24 25 def create_message_and_publish(author, message) 26 if self.active 27 m = self.messages.create(a: author, m: message) 28 publish_to "/streams/#{self.id}", m.to_json 29 end 30 end 31 end app/models/stream.rb
  5. 1 = subscribe_to "/streams/#{@stream.id}" 2 3 %ul#stream 4 .new_messages 5

    .previous_messages 6 - @messages.each do |message| 7 = render 'liveblogs/message', :message => message 8 9 :javascript 46 PrivatePub.subscribe("/streams/#{@stream.id}", function(data, channel) { 47 data = jQuery.parseJSON(data); 48 $(".new_messages").prepend("<li><span class='timestamp'>" + 49 data.t.slice(11,16) + "</span>\n" + 50 "<span class='author'>" + data.a + "</span>\n" + 51 data.m + "</li>").children(":first").hide().fadeIn('slow'); 52 }); app/views/liveblogs/show.html.haml