Skip to content

Instantly share code, notes, and snippets.

@channainfo
Created February 23, 2021 07:14
Show Gist options
  • Save channainfo/70c591a40e25f005fc5b57474e4e14fb to your computer and use it in GitHub Desktop.
Save channainfo/70c591a40e25f005fc5b57474e4e14fb to your computer and use it in GitHub Desktop.
Feed top products per vendor spree
module Feed
class VendorProduct
attr_accessor :vendor
LIMIT = 4
def initialize(vendor:, products:)
@vendor = vendor
@products = products
end
def products
@products.blank? ? [] : @products
end
def self.call(vendor_ids, options={} )
limit = options[:limit] || LIMIT
return [] if vendor_ids.blank?
vendors = Spree::Vendor.includes(:translations).find(vendor_ids)
sub_query = query_product_in_vendor(vendor_ids).to_sql
vendor_products = Spree::Product.select("*").from(" ( #{sub_query} ) AS spree_products")
.where(["spree_products.product_top_rank <= ?", limit])
.includes(:translations, master: :prices)
vendor_products = vendor_products.to_a
vendors.map do |vendor|
products = vendor_products.select{|vendor_product| vendor_product.vendor_id == vendor.id}
Feed::VendorProduct.new(vendor: vendor, products: products)
end
end
def self.query_product_in_vendor(vendor_ids)
select_stm = "spree_products.*, DENSE_RANK() OVER( PARTITION BY vendor_id ORDER BY created_at DESC ) AS product_top_rank"
Feed::query_active_products.select(select_stm)
.where(vendor_id: vendor_ids )
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment