Search code examples
ruby-on-railsruby-on-rails-3.1faye

How to create a new channel with Faye, and then access it via a url or model?


I'm using faye based on this tutorial to create a chat message system. The only thing is, I want different channels "chatrooms" that users can subscribe to by visiting their url. Also, I want to represent each channel with a model, so that I can find them by name or index. How do I do this? For some reason, I can't find any good resources on this. By the way, I'm not terribly new to Rails, I just don't know how to use Faye at all.

Here's my use case, just to be clear:

User visits my site.

User enters "chat1" into a form, which lets say accesses the Chatrooms controller, index action

Controller finds all Chatrooms by name "chat1"

If it can't find it, it instantiates a new chatroom called "chat1" and subscribes the user to it

Redirects user to that chatroom.


Solution

  • Faye seems to automatically create new channels when you ask to subscribe to them. In your javascript, instead of subscribing to "foo" for example, do this:

    var channel_name = "/chatrooms/"+"<%= @chatroom.id %>";
        // Subscribe to the public channel
        var public_subscription = client.subscribe(channel_name, function(data) {
          $('<p></p>').html(data.username + ": " + data.msg).appendTo('#blab_box');
         });