Module: Redstream::Model::ClassMethods

Defined in:
lib/redstream/model.rb

Instance Method Summary collapse

Instance Method Details

#redstream_callbacks(producer: Producer.new) ⇒ Object

Adds after_save, after_touch, after_destroy and, most importantly, after_commit callbacks. after_save, after_touch and after_destroy write a delay message to a delay stream. The delay messages are exactly like other messages, but will be read and replayed by a Redstream::Delayer only after a certain amount of time has passed (5 minutes usually) to fix potential inconsistencies which result from network or other issues in between database commit and the rails after_commit callback.

Parameters:

  • producer (Redstream::Producer) (defaults to: Producer.new)

    A Redstream::Producer that is responsible for writing to a redis stream



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/redstream/model.rb', line 33

def redstream_callbacks(producer: Producer.new)
  after_save    { |object| instance_variable_set(IVAR_DELAY_MESSAGE_ID, producer.delay(object)) if object.saved_changes.present? }
  after_touch   { |object| instance_variable_set(IVAR_DELAY_MESSAGE_ID, producer.delay(object)) }
  after_destroy { |object| instance_variable_set(IVAR_DELAY_MESSAGE_ID, producer.delay(object)) }

  after_commit(on: [:create, :update]) do |object|
    if object.saved_changes.present?
      producer.queue(object)

      if id = instance_variable_get(IVAR_DELAY_MESSAGE_ID)
        producer.delete(object, id)
        remove_instance_variable(IVAR_DELAY_MESSAGE_ID)
      end
    end
  end

  after_commit(on: :destroy) do |object|
    producer.queue(object)

    if id = instance_variable_get(IVAR_DELAY_MESSAGE_ID)
      producer.delete(object, id)
      remove_instance_variable(IVAR_DELAY_MESSAGE_ID)
    end
  end
end

#redstream_nameObject



59
60
61
# File 'lib/redstream/model.rb', line 59

def redstream_name
  name.pluralize.underscore
end