Created
October 25, 2022 11:47
-
-
Save katakeynii/738e9715140a125378d17f26bf55b273 to your computer and use it in GitHub Desktop.
This file contains 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
require 'delegate' | |
# On crée notre classe délégator | |
class MyDelegator < Delegator | |
# retourne l'objet à qui on a déléguer les fonctions | |
def __getobj__ | |
@delegate_sd_obj | |
end | |
# permet de changer l'objet à qui on délégue la fonction | |
def __setobj__(obj) | |
@delegate_sd_obj = obj | |
end | |
end | |
# Ici notre class produit hérite de notre delegotr | |
class Product < MyDelegator | |
attr_accessor :name, :variants | |
def initialize price, sku, | |
master = Variant.new(price: price, sku: sku, is_master: true) | |
@variants = [master] | |
__setobj__(master) | |
end | |
def set_variant sku | |
variant = @variants.find {|v| v.sku.eql?(sku) } | |
if variant | |
__setobj__(variant) | |
end | |
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: 9550, sku: "B2") | |
prod = Product.new(3000, "MASTER") | |
prod.add_variant(variant) | |
prod.add_variant(variant2) | |
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment