Created
October 26, 2022 11:01
-
-
Save katakeynii/c71a10306aa7fe22dc24bd8d93093f96 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Variant | |
attr_accessor :price, :sku, :is_master, :product | |
delegate :name, to: :@product, allow_nil: true, prefix: "product" | |
def initialize(data={}) | |
@price = data[:price] | |
@sku = data[:sku] | |
@is_master = data[:is_master] || false | |
@product = data[:product] | |
end | |
end | |
# Ici notre class produit hérite de notre delegotr | |
class Product | |
attr_accessor :name | |
delegate :price, :sku, to: :@obj | |
delegate :count, :map, to: :@variants, prefix: "variant" | |
def initialize name, price, sku, | |
master = Variant.new(price: price, sku: sku, is_master: true) | |
@variants = [master] | |
@name = name | |
@obj = master # ici on donne à @obj l'objet à qui on va déléguer les fonction | |
end | |
# Pas de changement | Ici on change de d'objet à qui on délégue | |
def set_variant sku | |
variant = @variants.find {|v| v.sku.eql?(sku) } | |
@obj = variant unless variant.nil? | |
end | |
def add_variant(variant) | |
variant.product = self | |
@variants << variant | |
end | |
end | |
variant = Variant.new(price: 1000, sku: "BX") | |
variant2 = Variant.new(price: 9550, sku: "B2") | |
puts variant.product_name # nil // On a nil comme resultant car on a autorisé le fait de pouvoir retourner le nil | |
prod = Product.new("Tshirt DRB", 3000, "MASTER") | |
prod.add_variant(variant) | |
prod.add_variant(variant2) | |
puts variant.product_name # Tshirt DRB | |
puts prod.price # 3000 // price of the master with SKU MASTER | |
prod.set_variant("B2") # On change pour sélectionner un autre variant | |
puts prod.price # 9550 // price of the master with SKU B2 | |
puts prod.variant_count # 3 | ceci nous donne le nombre de variants | |
puts prod.variant_map(&:sku) # |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment