Module: Shrine::Plugins::AtomicHelpers::AttacherClassMethods

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

Instance Method Summary collapse

Instance Method Details

#retrieve(model: nil, entity: nil, name:, file:, **options) ⇒ Object

Retrieves the attacher from the given entity/model and verifies that the attachment hasn't changed. It raises `Shrine::AttachmentChanged` exception if the attached file doesn't match.

Shrine::Attacher.retrieve(model: photo, name: :image, file: file_data)
#=> #<ImageUploader::Attacher>

17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/shrine/plugins/atomic_helpers.rb', line 17

def retrieve(model: nil, entity: nil, name:, file:, **options)
  fail ArgumentError, "either :model or :entity is required" unless model || entity

  record = model || entity

  attacher   = record.send(:"#{name}_attacher", **options) if record.respond_to?(:"#{name}_attacher")
  attacher ||= from_model(record, name, **options) if model
  attacher ||= from_entity(record, name, **options) if entity

  if attacher.file != attacher.uploaded_file(file)
    fail Shrine::AttachmentChanged, "attachment has changed"
  end

  attacher
end