Advertisement
B_Stonebridge

shopify script - count cart items by tag

Feb 25th, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.26 KB | None | 0 0
  1. # enumerate and count by tag
  2.  
  3. # get items matching tag "x" from cart as array[]
  4. product_x_items = Input.cart.line_items.select do |line_item|
  5.     product = line_item.variant.product # get product
  6.    
  7.     !product.gift_card? && product.tags.include?("x") # return boolean to selector
  8. end
  9.  
  10. # get total number of items
  11. match_count = product_x_items.inject(0) { |sum, p| sum + p.quantity } # https://apidock.com/rails/Enumerable/sum
  12.  
  13. puts "Items matching x:"
  14. puts match_count # print value to the console
  15.  
  16. # ---
  17.  
  18. # enumerate and count by tags
  19.  
  20. # tags to match
  21. DISCOUNT_TAGS = [ "discount_1", "discount_2" ]
  22.  
  23. tagged_items = Input.cart.line_items.select do |line_item|
  24.     product = line_item.variant.product # get product
  25.    
  26.     # compare product tags and tags we're looking for, either method below works
  27.     # https://apidock.com/ruby/Array/include%3F
  28.     !product.gift_card? && product.tags & DISCOUNT_TAGS != [] # return boolean
  29.     #!product.gift_card? && product.tags.any? { |i| DISCOUNT_TAGS.include?(i) } # return boolean
  30. end
  31.  
  32. # get total number of items
  33. tagged_items_count = tagged_items.inject(0) { |sum, p| sum + p.quantity } # https://apidock.com/rails/Enumerable/sum
  34.  
  35. puts "Tagged Items:"
  36. puts tagged_items_count # print value to the console
  37.  
  38. Output.cart = Input.cart
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement