module ModelUpdates::ModelExtensions::ClassMethods

Public Instance Methods

model_updates_broadcast_attributes(args) click to toggle source
# File lib/model_updates/model_extensions.rb, line 11
def model_updates_broadcast_attributes(args)
  model_updates_data[:attributes] = args.fetch(:attributes)

  # Need to remember what changes before callbacks, since it might get changed by gems like AwesomeNestedSet before after_commit is called
  before_update do
    attribute_changes = {}

    args.fetch(:attributes).each do |attribute_name|
      method_changed = "saved_changed_to_#{attribute_name}?"
      next if respond_to?(method_changed) && !__send__(method_changed)

      attribute_changes[attribute_name] = __send__(attribute_name)
    end

    @_model_updates_changes = attribute_changes
  end

  after_commit on: :update do |model|
    attribute_changes = @_model_updates_changes
    @_model_updates_changes = nil

    if attribute_changes.any?
      ModelUpdates::UpdateChannel.broadcast_to(
        model,
        id: id,
        model: model.class.name,
        changes: attribute_changes,
        type: :update
      )
    end
  end
end
model_updates_broadcast_created() click to toggle source
# File lib/model_updates/model_extensions.rb, line 44
def model_updates_broadcast_created
  after_commit on: :create do |model|
    channel_name = "ModelUpdatesCreate#{model.class.name}"

    attributes = {}
    model.class.model_updates_data[:attributes].each do |attribute_name|
      attributes[attribute_name] = __send__(attribute_name)
    end

    ActionCable.server.broadcast(
      channel_name,
      id: id,
      attributes: attributes
    )
  end
end
model_updates_broadcast_destroyed() click to toggle source
# File lib/model_updates/model_extensions.rb, line 61
def model_updates_broadcast_destroyed
  after_commit on: :destroy do |model|
    attributes = {}
    model.class.model_updates_data[:attributes].each do |attribute_name|
      attributes[attribute_name] = __send__(attribute_name)
    end

    ModelUpdates::UpdateChannel.broadcast_to(
      model,
      id: id,
      model: model.class.name,
      attributes: attributes,
      type: :destroy
    )
  end
end
model_updates_call(event_name, args = {}) click to toggle source
# File lib/model_updates/model_extensions.rb, line 78
def model_updates_call(event_name, args = {})
  ActionCable.server.broadcast(
    "model_updates_events_class_#{name}",
    event_name: event_name,
    model: name,
    callback_type: "model_class",
    args: args
  )
end
model_updates_data() click to toggle source
# File lib/model_updates/model_extensions.rb, line 7
def model_updates_data
  @model_updates_data ||= {}
end