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
4

3 に答える 3

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
于 2013-04-15T12:17:33.353 に答える
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
于 2013-04-15T12:08:13.417 に答える