module Entangled::Model::InstanceMethods

Public Instance Methods

as_json(options = nil) click to toggle source

Override the as_json method so that the JSON representation of the resource includes its errors. This is necessary so that errors are sent back to the client along with the resource on create and update. Furthermore, keys are converted to camel case, to comply with JavaScript conventions on the client

Calls superclass method
# File lib/entangled/model.rb, line 74
def as_json(options = nil)
  super(options || attributes).merge(errors: errors).as_json.
    to_camelback_keys
end
channels(tail = '') click to toggle source

Build channels. Channels always at least include a collection channel, i.e. /tacos, and a member channel, i.e. /tacos/1, for direct access.

If the model belongs_to other models, nested channels are created for all parents, grand parents, etc recursively

# File lib/entangled/model.rb, line 86
def channels(tail = '')
  channels = []

  # If the record is new, it should not have any channels
  return channels if new_record?

  plural_name = self.class.name.underscore.pluralize

  # Add collection channel for child only. If the tails
  # is not empty, the function is being called recursively
  # for one of the parents, for which only member channels
  # are needed
  if tail.empty?
    collection_channel = "/#{plural_name}" + tail
    channels << collection_channel
  end

  # Add member channel
  member_channel = "/#{plural_name}/#{to_param}" + tail
  channels << member_channel

  # Add nested channels for each parent
  parents.each do |parent|
    # Only recusively add collection channel
    # for child
    if tail.empty?
      channels << parent.channels(collection_channel)
    end

    channels << parent.channels(member_channel)
  end

  channels.flatten
end

Private Instance Methods

json(action) click to toggle source

JSON containing the type of action (:create, :update or :destroy) and the record itself. This is eventually broadcast to the client

# File lib/entangled/model.rb, line 134
def json(action)
  {
    action: action,
    resource: self
  }.to_json
end
parents() click to toggle source

Find parent classes from belongs_to associations that are not nil

# File lib/entangled/model.rb, line 143
def parents
  self.class.
    reflect_on_all_associations(:belongs_to).
    map{ |a| send(a.name) }.
    reject(&:nil?)
end
publish(action) click to toggle source

Publishes to client. Whoever is subscribed to the model’s channels gets the message

# File lib/entangled/model.rb, line 125
def publish(action)
  channels.each do |channel|
    redis.publish(channel, json(action))
  end
end