Module: ActionCableNotifications::Model::ClassMethods

Defined in:
lib/action_cable_notifications/model.rb

Instance Method Summary collapse

Instance Method Details

#broadcast_notifications_from(broadcasting, options = {}) ⇒ Object

Sets or removes notificacions options for Active Record model

Parameters:

  • broadcasting (sym)

    Topic name to broadcast in

  • options (hash) (defaults to: {})

    Hash containing notification options



24
25
26
27
28
29
30
31
32
# File 'lib/action_cable_notifications/model.rb', line 24

def broadcast_notifications_from ( broadcasting, options = {} )
  # Default options
  options = {
    actions: [:create, :update, :destroy],
    scope: :all             # Default collection scope
    }.merge(options)

  self.ActionCableNotificationsOptions[broadcasting.to_s] = options
end

#notify_initial(broadcasting) ⇒ Hash

Retrieves initial values to be sent to clients upon subscription

collection: self.model_name.collection,
msg: 'add_collection',
data: self.scoped_collection(options[:scope])

Parameters:

  • broadcasting (Sym)

    Name of broadcasting stream

Returns:

  • (Hash)

    Hash containing the results in the following format:



58
59
60
61
62
63
64
65
66
67
# File 'lib/action_cable_notifications/model.rb', line 58

def notify_initial ( broadcasting )
  options = self.ActionCableNotificationsOptions[broadcasting.to_s]
  if options.present?
    {
      collection: self.model_name.collection,
      msg: 'upsert_many',
      data: self.scoped_collection(options[:scope])
    }
  end
end

#scoped_collection(scope = :all) ⇒ ActiveRecordRelation

Returns collection scoped as specified in parameters.

example: [[:limit, 5], [:order, :id]]

Parameters:

  • scope (Array) (defaults to: :all)

    Contains the scopes to be applied. For

Returns:

  • (ActiveRecordRelation)

    Results fetched from the database



42
43
44
45
# File 'lib/action_cable_notifications/model.rb', line 42

def scoped_collection ( scope = :all )
  scope = scope.to_a if scope.is_a? Hash
  Array(scope).inject(self) {|o, a| o.try(*a)} rescue nil
end