Module: Spree::HasLibraryMedia
- Extended by:
- ActiveSupport::Concern
- Included in:
- Category, Collection
- Defined in:
- app/models/concerns/spree/has_library_media.rb
Overview
Puts a model's named image slots in the media library.
A file uploaded straight to a category's image slot used to exist only as
an ActiveStorage attachment — in storage but invisible to the library: no
grid entry, no search, no reuse. Declaring the slots here keeps them
reconciled with real Spree::Media placements (+viewable+ = this record)
sharing the slot blobs, so the library sees what the merchant uploaded and
can hand the file to anything else.
The named attachments remain the operational storage every serializer and storefront reads; the placements are the library's view of them. Clearing or replacing a slot UNPLACES its row — back to the library pool — rather than destroying it, because the merchant's file outliving one use is the point of having a library.
include Spree::HasLibraryMedia
has_library_media :image, :square_image
Until a real gallery arrives for these models, reconciliation owns every placement on the record: a row whose blob no slot holds is unplaced. A future gallery replaces the slots as the source of truth and this concern dissolves into it.
Instance Method Summary collapse
-
#sync_library_media! ⇒ void
Reconciles this record's placements against its slots: a slot blob with no placement gains one, a placement whose blob no slot holds is unplaced.
Instance Method Details
#sync_library_media! ⇒ void
This method returns an undefined value.
Reconciles this record's placements against its slots: a slot blob with no placement gains one, a placement whose blob no slot holds is unplaced. Runs on save when a slot changed; callable directly for backfills.
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
# File 'app/models/concerns/spree/has_library_media.rb', line 54 def sync_library_media! desired_blobs = library_media_slots.each_with_object({}) do |slot, blobs| = public_send(slot) blobs[.blob.id] ||= .blob if .attached? end media.includes(attachment_attachment: :blob).each do |placement| blob_id = placement.&.id next if blob_id && desired_blobs.delete(blob_id) placement.update!(viewable: nil) end desired_blobs.each_value do |blob| placement = Spree::Media.new(viewable: self, alt: blob.filename.to_s) placement..attach(blob) placement.save! end end |