Skip to content
Eric Draut edited this page Dec 28, 2015 · 20 revisions

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.

Use It

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>
Clone this wiki locally