Module: ModelUpdates::ModelExtensions::ClassMethods

Defined in:
lib/model_updates/model_extensions.rb

Instance Method Summary collapse

Instance Method Details

#model_updates_broadcast_attributes(args) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# 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_save on: :update do
    attribute_changes = {}

    args.fetch(:attributes).each do |attribute_name|
      method_changed = "#{attribute_name}_changed?"
      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_createdObject



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/model_updates/model_extensions.rb', line 43

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_destroyedObject



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/model_updates/model_extensions.rb', line 60

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 = {}) ⇒ Object



77
78
79
80
81
82
83
84
85
# File 'lib/model_updates/model_extensions.rb', line 77

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_dataObject



7
8
9
# File 'lib/model_updates/model_extensions.rb', line 7

def model_updates_data
  @_model_updates ||= {}
end