2013-04-15 52 views
0

我在想,我怎么能重构这个代码,因为它没有看起来不错的阅读和理解重构轨方法

def next_payment_price 
    price = self.plan_price 
    price = discounted_price if self.coupon && self.coupon_duration.nil? && self.coupon_discount != 100 
    price = discounted_price if self.coupon && self.coupon_duration.present? && self.coupon_discount != 100 && ((self.created_at + 14.days + self.coupon_duration.month) > Time.now) 
    price 
end 

def discounted_price 
    self.plan_price - ((self.plan_price * self.coupon_discount)/100) 
end 
+0

提取这优惠券类 – apneadiving

+0

无法实现,因为优惠券是可以改变的,而在这个类中,我有静态数据,这将用于计算 –

+0

是的...但是你可以用你的细节初始化一个优惠券对象,提醒:解耦你的lpgic,用它们创建对象自己的责任。 (基本上,人们鼓励你保持模型中的逻辑不要遵守这些准则) – apneadiving

回答

3

我认为你可以使用更小的方法来更好的阅读

def next_payment_price 
    correct_discount? && correct_coupon? ? discounted_price : self.plan_price 
    end 

    def expired_coupon? 
    (self.created_at + 14.days + self.coupon_duration.month) < Time.now 
    end 

    def correct_coupon? 
    self.coupon_duration.nil? || (self.coupon_duration && !expired_coupon?) 
    end 

    def correct_discount? 
    self.coupon && self.coupon_discount && self.coupon_discount < 100 
    end 

    def discounted_price 
    self.plan_price - self.plan_price * self.coupon_discount/100 
    end 
1

我建议你创建coupon模型内部的小方法,给出了对象更多的含义,如:

def is_less_than_100? 
    self.coupon_discount != 100 
end 

def is_date_bigger_than_today? 
    (self.created_at + 14.days + self.coupon_duration.month) > Time.now 
end 

这样,您将有更少的代码,它会更容易理解:

price = discounted_price if self.is_less_than_100? and self.is_date_bigger_than_today? 

P.S .:这些名称仅用于说明目的。我认为你有这个想法

1

如果你把失效逻辑抽出来做一个方法呢?

def not_expired? 
     return false if self.coupon_duration.nil? 
     ((self.created_at + 14.days + self.coupon_duration.month) > Time.now) 
    end 

然后:

def next_payment_price 
     price = self.plan_price 
     price = discounted_price if self.coupon? and not_expired? ... 
    end