Last active
October 26, 2022 09:40
-
-
Save katakeynii/513e466df6dda532df151e8edf366034 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
require 'forwardable' | |
# Ici notre class produit hérite de notre delegotr | |
class Product | |
extend Forwardable | |
attr_accessor :name, :variants | |
def_delegators :@obj, :price, :sku | |
def initialize price, sku, | |
master = Variant.new(price: price, sku: sku, is_master: true) | |
@variants = [master] | |
@obj = master # ici on donne à @obj l'objet à qui on va déléguer les fonction | |
end | |
# Ici on change de d'objet à qui on délégu | |
def set_variant sku | |
variant = @variants.find {|v| v.sku.eql?(sku) } | |
@obj = variant unless variant.nil? | |
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