Skip to content

Instantly share code, notes, and snippets.

@BellandWhistle
Created June 7, 2011 03:40
Show Gist options
  • Save BellandWhistle/1011641 to your computer and use it in GitHub Desktop.
Save BellandWhistle/1011641 to your computer and use it in GitHub Desktop.
Faye and Ruby on Rails 3
<head>
...
<%= javascript_include_tag 'http://localhost:9292/faye.js' %>
</head>
require 'faye'
faye_server = Faye::RackAdapter.new(:mount => '/faye', :timeout => 45)
run faye_server
gem 'faye', '0.6.1'
<% javascript_tag do %>
$(function() {
var client = new Faye.Client('http://localhost:9292/faye');
client.subscribe("<%= project_path(@project) %>", function(data) {
// do stuff here when receives the data
});
});
<% end %>
<% javascript_tag do %>
$(function() {
var client = new Faye.Client('http://localhost:9292/faye');
client.subscribe("<%= project_path(@project) %>", function(data) {
var task_view = $('#task-'+ data.task_id).remove();
$('#'+ data.task_state + '-tasks').append(task_view).fadeIn();
});
});
<% end %>
#Using Faye HTTP interface
def update
@task = Task.find(params[:id])
if @task.update_attributes(params[:task])
message = {:channel => project_path(@task.project), :data => { :task_id => @task.id, :task_state => @task.state}}
uri = URI.parse("http://localhost:9292/faye")
Net::HTTP.post_form(uri, :message => message.to_json)
end
render :nothing => true
end
#Using Faye client on server
require 'eventmachine'
class TasksController < ApplicationController
...
def update
...
if @task.update_attributes(params[:task])
client = Faye::Client.new('http://localhost:9292/faye')
client.publish(project_path(@project), 'text' => 'Update html view!')
else
#show errors
end
...
end
...
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment