Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Extend `Spree::Asset` with helpful methods for active storage attachments

Damian Legawiec0c87ca3904f2
diff --git a/core/app/models/spree/asset.rb b/core/app/models/spree/asset.rb
index 29f5177974..8c6c5c7a0f 100644
--- a/core/app/models/spree/asset.rb
+++ b/core/app/models/spree/asset.rb
@@ -9,6 +9,8 @@ module Spree
belongs_to :viewable, polymorphic: true, touch: true
acts_as_list scope: [:viewable_id, :viewable_type]
+ delegate :key, :attached?, :variant, :variable?, :blob, :filename, to: :attachment
+
if Spree.public_storage_service_name
has_one_attached :attachment, service: Spree.public_storage_service_name
else
@@ -16,5 +18,9 @@ module Spree
end
default_scope { includes(attachment_attachment: :blob) }
+
+ def product
+ @product ||= viewable_type == 'Spree::Variant' ? viewable&.product : nil
+ end
end
end
diff --git a/core/spec/models/spree/asset_spec.rb b/core/spec/models/spree/asset_spec.rb
index 1c966777bf..2f214022aa 100644
--- a/core/spec/models/spree/asset_spec.rb
+++ b/core/spec/models/spree/asset_spec.rb
@@ -2,4 +2,51 @@ require 'spec_helper'
describe Spree::Asset, type: :model do
it_behaves_like 'metadata'
+
+ describe '#product' do
+ it 'returns the product for the asset' do
+ variant = create(:variant)
+ asset = create(:asset, viewable: variant)
+ expect(asset.product).to eq(variant.product)
+ end
+ end
+
+ describe 'delegated methods' do
+ let(:asset) { create(:image) }
+ let(:attachment) { asset.attachment }
+
+ before do
+ allow(asset).to receive(:attachment).and_return(attachment)
+ end
+
+ it 'delegates :key to attachment' do
+ expect(attachment).to receive(:key)
+ asset.key
+ end
+
+ it 'delegates :attached? to attachment' do
+ expect(attachment).to receive(:attached?)
+ asset.attached?
+ end
+
+ it 'delegates :variant to attachment' do
+ expect(attachment).to receive(:variant)
+ asset.variant
+ end
+
+ it 'delegates :variable? to attachment' do
+ expect(attachment).to receive(:variable?)
+ asset.variable?
+ end
+
+ it 'delegates :blob to attachment' do
+ expect(attachment).to receive(:blob)
+ asset.blob
+ end
+
+ it 'delegates :filename to attachment' do
+ expect(attachment).to receive(:filename)
+ asset.filename
+ end
+ end
end