-
Notifications
You must be signed in to change notification settings - Fork 0
Home
Foreign Office is a client push library for Rails. It allows you to have side effects on your client while keeping all business logic on your servers.
Broadcasters and Listeners Foreign Office consists of broadcasters, usually service models that you create to broadcast state from models on the server, and listeners, which allow you to receive content or execute common behaviors on the client based on the state that is broadcast by the server.
Let's say you add friendships via an ajax call, and the ajax response uses the Thin Man pattern of a single representation of the object, which is inserted into the friendship list. In order to maintain that simplicity, Foreign Office handles the side effect of updating the friendship counter.
In your model
class User < ActiveRecord::Base
has_many :friendships
def serialize
self.attributes.merge friend_count: self.friendships.count
end
end
In a service object, called from your controller
class AddFriend
def init(initiator,new_friend)
@initiator, @new_friend = initiator, new_friend
end
def call
@friendship = Friendship.create(initiator: @initiator, friend: @new_friend)
@recipient.broadcast_change
@new_friend.broadcast_change
@friendship
end
end
In your view
You have <span <%= listener_attrs(@user, :friend_count) %> >
<%= @user.friendships.count %></span> friendships
<section id="friendship_list">
<%= render partial: '/friendships/show_wrapper', collection: @user.friendships %>
</section>
Add a message bus:
gem 'pubnub'
Pusher is also an option. Integrating your own message bus is fairly straightforward, you need a class that responds to publish
and config
, then you pass is as the klass
as in the config example below. Contact us if you have questions or want to add another SaaS message bus as a default option in Foreign Office.
Here's an example of connecting a Pubnub account to Foreign Office:
ForeignOffice.config({
bus: {
klass: ForeignOffice::Busses::PubnubBus,
publish_key: ENV['PUBNUB_PUBLISH_KEY'],
subscribe_key: ENV['PUBNUB_SUBSCRIBE_KEY'],
secret_key: ENV['PUBNUB_SECRET_KEY']
}
})
Naturally you must set the keys in your environment for this to work.