[英]Understanding method calls in ruby
我有兩節課
class Cart
belongs_to :coupon
end
class Coupon
has_many :carts
def discount
end
end
我執行
cart = Cart.last.coupon.discount
在不將購物車作為參數傳遞的情況下,如何知道它在折扣方法內?
那就是我的方法:
class Cart
belongs_to :coupon
def discount
coupon.discount(self) unless coupon.nil?
end
end
class Coupon
has_many :carts
def discount(cart)
# use the coupon discount logic to apply discount on particular cart
end
end
你不能從優惠券。 我建議您在購物車內委派折扣。
class Cart
belongs_to :coupon
delegate :discount, to: coupon
end
class Coupon
has_many :carts
def discount
end
end
那么你也能
discount = cart.discount
但是,請注意,委托是Rails方法。 我假設,當您使用belongs_to和標記為ruby-on-rails時,您就在rails之內。 但是,如果沒有,這也將起作用:
class Cart
belongs_to :coupon
def discount
coupon.discount if coupon
end
end
AFAIK無法做到,即使可以,這也是一個可怕而脆弱的駭客。 使用折扣方式時,您將無權再訪問特定的購物車,而只能訪問與優惠券關聯的所有購物車。 如果那只是一輛車,那您真幸運。
為了減少耦合並更好地遵守Demeter定律,我建議在購物車上創建一種折扣方法
def discount
coupon.discount(self)
end
另一個選擇可能是擁有另一個ActiveRecord類,我們將其稱為CouponActivation,位於中間,該類將購物車和優惠券關聯起來,並自行計算折扣。
購物車屬於CouponActivation,CouponActivation有一個購物車並屬於Coupon,Coupon有許多CouponActivations和很多通過CouponActivations的購物車。 您將折扣方法放入CouponActivation中,並可以訪問所需的信息。
仍然建議僅傳遞值。 更容易,更清晰,更容易測試。
我認為您采用的方法不好。 如果優惠券是對象,可以為您提供購物車總價的折扣,那么我將使用以下方式:
class Cart
has_and_belongs_to_many :coupons
def calculate_discount
#this is place where you can get rid of double coupons or coupons that are not allowed together
for coupon in coupons
coupon.apply_discount_to(self)
end
end
end
class Coupon
has_and_belongs_to_many :carts
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.