Created
October 24, 2022 16:28
-
-
Save katakeynii/59465fd128d8a3f5077b7bf690aae262 to your computer and use it in GitHub Desktop.
product_with_method_missing
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 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 | |
def method_missing method, *args | |
master = @variants.find {|v| v.is_master} | |
if master.respond_to?(method) | |
master.send(method, *args) | |
end | |
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 # 3000 // price of the master |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment