Skip to content

Instantly share code, notes, and snippets.

@BenMorganIO
Created September 19, 2014 22:57
Show Gist options
  • Select an option

  • Save BenMorganIO/ad1f5f206833f06ffa12 to your computer and use it in GitHub Desktop.

Select an option

Save BenMorganIO/ad1f5f206833f06ffa12 to your computer and use it in GitHub Desktop.
Creating a factorial hash of variants of a product to JS in Spree
def product_variants
products = Spree::Taxon.find_by(name: 'Donations').products
product_hash = {}
variants = -> (product) do
variant_hash = {}
option_values = -> (option_type) do
option_value_hash = {}
option_type.option_values.each do |option_value|
option_value_variants = option_value.variants.to_a.keep_if do |variant|
variant.product.id == product.id
end
option_value_hash[option_value.name] = option_value_variants.map(&:gon_object)
end
option_value_hash
end
product.option_types.each_with_index do |option_type, index|
variant_hash[option_type.name] = option_values.call(option_type)
end
variant_hash
end
products.each do |product|
product_hash[product.id] = variants.call(product)
end
product_hash
end
# You would access these through a Rails-to-JS data window such as Gon.
# > gon
# Object {variants: Object}
# You would be able to set your variants via `gon.variants = Spree::Product.product_variants` in your controller.
# This would give you this result in the console (assuming that you have 8 products.
# > gon.variants
# Object {1: Object, 2: Object, 3: Object, 4: Object, 5: Object, 6: Object, 7: Object, 8: Object}
# We access the variants of a product through the ID of the product. This gives us a listing of all the option types.
# > gon.variants['1']
# Object {goodie-options: Object, share-name: Object}
# After we have asked for the option types, we see a list of the option values
# > gon.variants['1']['goodie-options']
# Object {yes: Array[2], no: Array[2]}
# Once inside of the option value, we see an array of objects which are variants
# > gon.variants['1']['goodie-options']['yes']
# [Object, Object]
# And here's the variant:
# > gon.variants['1']['goodie-options']['yes'][0]
# Object {sku: "123489", weight: 0, height: 0, width: 0, depth: 0…}
# There will need to be a comparison of the variants between the option values selected.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment