Module: Shrine::Plugins::AtomicHelpers::AttacherMethods

Defined in:
lib/shrine/plugins/atomic_helpers.rb

Instance Method Summary collapse

Instance Method Details

#abstract_atomic_persist(original_file = file, reload:, persist:) ⇒ Object

Reloads the record to check whether the attachment has changed. If it hasn’t, it persists the record. Otherwise it raises ‘Shrine::AttachmentChanged` exception.

attacher.abstract_atomic_persist(
  reload:  reload_strategy,
  persist: persist_strategy,
)

This more convenient to use with concrete persistence plugins, which provide defaults for reloading and persistence.



71
72
73
74
75
76
77
78
79
80
81
# File 'lib/shrine/plugins/atomic_helpers.rb', line 71

def abstract_atomic_persist(original_file = file, reload:, persist:)
  abstract_reload(reload) do |attacher|
    if attacher && attacher.file != original_file
      fail Shrine::AttachmentChanged, "attachment has changed"
    end

    yield attacher if block_given?

    abstract_persist(persist)
  end
end

#abstract_atomic_promote(reload:, persist:, **options, &block) ⇒ Object

Like #promote, but additionally persists the promoted file atomically. You need to specify ‘:reload` and `:persist` strategies when calling the method:

attacher.abstract_atomic_promote(
  reload:  reload_strategy,
  persist: persist_strategy,
)

This more convenient to use with concrete persistence plugins, which provide defaults for reloading and persistence.



46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/shrine/plugins/atomic_helpers.rb', line 46

def abstract_atomic_promote(reload:, persist:, **options, &block)
  original_file = file

  result = promote(**options)

  begin
    abstract_atomic_persist(original_file, reload: reload, persist: persist, &block)
    result
  rescue Shrine::AttachmentChanged
    destroy_attached
    raise
  end
end

#file_dataObject

Return only needed main file data, without the metadata. This allows you to avoid bloating your background job payload when you have derivatives or lots of metadata, by only sending data you need for atomic persitence.

attacher.file_data #=> { "id" => "abc123.jpg", "storage" => "store" }


89
90
91
# File 'lib/shrine/plugins/atomic_helpers.rb', line 89

def file_data
  file!.data.reject { |key, _| key == "metadata" }
end