0

タイムスタンプに基づいて税率を取得しようとしています。Time クラスで「tax_rate」を定義する単純な mixin を実行しても意味がありません。「tax_rate」を「Government」クラス(またはモジュール?私がこれに慣れていないことはわかりません)に配置し、現在の時刻を想定するオプションを使用してメソッドを Time クラスで使用できるようにする方が理にかなっています単独で使用する場合。

例:

Time.now.tax_rate== 0.13
10.years_ago.tax_rate== 0.10
Government.tax_rate== 0.13(Time.now を想定)

メソッド tax_rate は次のとおりです。

def self.tax_rate
  t = self || Time.now # I know this part won't work properly, I'll fix it later. I want it to default to using the current Time object or if the method is used on its own, the current time.
  return 0.10 if t < Time.parse("July 1, 2001")
  return 0.12 if t < Time.parse("July 1, 2010")
  0.13
end

私は基本的に、Rails プロジェクトでさまざまなクラスの税率を参照する必要がありますが、それをモデルの 1 つに直接入れるのは適切ではないと感じています。それはそれ自身である必要があります。

4

1 に答える 1

1

TaxRateモジュールを持たないのはなぜですか?

module TaxRate
  def self.get t = Time.now
    t = Time.parse(t) if t.kind_of?(String)
    case
    when t < Time.parse("July 1, 2001") then 0.10
    when t < Time.parse("July 1, 2010") then 0.12
    else 0.13
    end
  end
end

TaxRate.get #=> 0.13
TaxRate.get(Time.now) #=> 0.13
TaxRate.get("July 1, 2000") #=> 0.10
TaxRate.get("July 1, 2012") #=> 0.13
TaxRate.get(10.years_ago) #=> 1.10

不自然だと思うtax_rateonを定義したい場合は、単に monkey patchです。TimeTime

class Time
  def tax_rate
    case
    when self < Time.parse("July 1, 2001") then 0.10
    when self < Time.parse("July 1, 2010") then 0.12
    else 0.13
    end
  end
end

Time.now.tax_rate #=> 0.13
10.years_ago.tax_rate #=> 0.10
于 2012-11-20T18:00:56.580 に答える