Is it possible to define two methods in a Rails model that require different initialization? -
hi i'm attempting create model in rails can perform 2 calculations. code:
class calculator def initialize(nair, cppy, interest_rate, payment, periods) @nair = nair.to_f / 100 @cppy = cppy.to_f @interest_rate = interest_rate @payment = payment @periods = periods end def effective refinance::annuities.effective_interest_rate(@nair, @cppy) end def principal refinance::annuities.principal(@interest_rate, @payment, @periods) end end
i have 2 forms reside in different views take input user including 'nair' , 'cppy' on 1 , 'interest_rate', 'payment' , 'periods' on other.
the problem i've run use model 5 arguments need available.
do need have separate models each calculation?
i'm complete beginning sorry if there obvious answer.
thanks!
there's dozen different ways solve this, 1 possible approach use default arguments in initialize method.
class calculator def initialize(nair=0, cppy=0, interest_rate=0, payment=0, periods=0) @nair = nair.to_f / 100 @cppy = cppy.to_f @interest_rate = interest_rate @payment = payment @periods = periods end def effective refinance::annuities.effective_interest_rate(@nair, @cppy) end def principal refinance::annuities.principal(@interest_rate, @payment, @periods) end end
another possible solution make them class methods , not deal instances or state:
class calculator def self.effective(nair, cppy) nair = nair.to_f / 100 cppy = cppy.to_f refinance::annuities.effective_interest_rate(nair, cppy) end def self.principal(interest_rate, payment, periods) refinance::annuities.principal(interest_rate, payment, periods) end end calculator.effective(x, y) calculator.principal(x, y, z)
Comments
Post a Comment