Skip to content

Instantly share code, notes, and snippets.

@katakeynii
Last active October 24, 2022 16:11
Show Gist options
  • Save katakeynii/a960526f852ad29f65a0a495d48fda7a to your computer and use it in GitHub Desktop.
Save katakeynii/a960526f852ad29f65a0a495d48fda7a to your computer and use it in GitHub Desktop.
Product With variants
class Product
attr_accessor :name, :variants
def initialize price, sku,
master = Variant.new(price: price, sku: sku, is_master: true)
@variants = [master]
end
def add_variant(variant)
@variants << variant
end
end
class Variant
attr_accessor :price, :sku, :is_master
def initialize(data={})
@price = data[:price]
@sku = data[:sku]
@is_master = data[:is_master] || false
end
end
variant = Variant.new(price: 1000, sku: "BX")
variant2 = Variant.new(price: 1000, sku: "B2")
prod = Product.new(3000, "MASTER")
prod.add_variant(variant)
prod.add_variant(variant2)
puts prod.variants.first.price # 3000 // price of the master
puts prod.variants.last.sku # B2 // sku of the third, last variant
puts prod.price # undefined method `price' for #<Product
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment