Last active
October 25, 2022 11:06
-
-
Save katakeynii/bd4c0a1e303e539d97e601216f0cb34a to your computer and use it in GitHub Desktop.
product_with_delegate_class
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" | |
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 | |
# Ici la classe produit hérite de la classe DelegateClass | |
class Product < DelegateClass(Variant) | |
attr_accessor :name, :variants | |
def initialize price, sku, | |
master = Variant.new(price: price, sku: sku, is_master: true) | |
@variants = [master] | |
# ici on appelle le constructeur de DelegateClass et | |
# on lui passe l'objet Variant a qui tout sera délégué | |
super(master) | |
end | |
def price | |
@variants.find {|v| v.is_master}.price | |
end | |
def add_variant(variant) | |
@variants << variant | |
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 # 3000 // price of the master |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment