Class: EmiCalculator::Calculator

Inherits:
Object
  • Object
show all
Defined in:
lib/emi_calculator/calculator.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(principal:, annual_rate:, tenure_months:) ⇒ Calculator



5
6
7
8
9
# File 'lib/emi_calculator/calculator.rb', line 5

def initialize(principal:, annual_rate:, tenure_months:)
  @principal = principal.to_f
  @annual_rate = annual_rate.to_f
  @tenure_months = tenure_months.to_i
end

Instance Attribute Details

#annual_rateObject (readonly)

Returns the value of attribute annual_rate.



3
4
5
# File 'lib/emi_calculator/calculator.rb', line 3

def annual_rate
  @annual_rate
end

#principalObject (readonly)

Returns the value of attribute principal.



3
4
5
# File 'lib/emi_calculator/calculator.rb', line 3

def principal
  @principal
end

#tenure_monthsObject (readonly)

Returns the value of attribute tenure_months.



3
4
5
# File 'lib/emi_calculator/calculator.rb', line 3

def tenure_months
  @tenure_months
end

Instance Method Details

#amortization_scheduleObject



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/emi_calculator/calculator.rb', line 34

def amortization_schedule
  schedule = []
  balance = principal
  r = monthly_rate
  (1..tenure_months).each do |month|
    interest = balance * r
    principal_component = emi - interest
    balance -= principal_component
    schedule << {
      month: month,
      emi: emi.round(3),
      interest: interest.round(3),
      principal: principal_component.round(3),
      balance: balance.positive? ? balance.round(3) : 0.000
    }
  end
  schedule
end

#emiObject



15
16
17
18
19
20
21
22
23
24
# File 'lib/emi_calculator/calculator.rb', line 15

def emi
  r = monthly_rate
  n = tenure_months
  p = principal

  return 0.00 if r.zero? || n.zero?

  rate = p * r * ((1+r)**n) / (((1+r)**n) - 1)
  rate.round(2)
end

#monthly_rateObject



11
12
13
# File 'lib/emi_calculator/calculator.rb', line 11

def monthly_rate
  annual_rate/ 12/ 100
end

#total_interestObject



30
31
32
# File 'lib/emi_calculator/calculator.rb', line 30

def total_interest
  total_payment - principal
end

#total_paymentObject



26
27
28
# File 'lib/emi_calculator/calculator.rb', line 26

def total_payment
  emi * tenure_months
end