Sha256: 6aa9cc09a293522cc7d0b6e5f935e1493bdb63c9c85b6819da699fc7b194401d

Contents?: true

Size: 1.88 KB

Versions: 2

Compression:

Stored size: 1.88 KB

Contents

# coding: utf-8
module LoanCreator
  class Timetable
    # Used to calculate next term's date (see ActiveSupport#advance)
    PERIODS = {
      month:    {months: 1},
      quarter:  {months: 3},
      semester: {months: 6},
      year:     {years: 1}
    }

    attr_reader :terms, :starts_on, :period, :starting_index #, :interests_start_date

    def initialize(starts_on:, period:, interests_start_date: nil, starting_index: 1)
      raise ArgumentError.new(:period) unless PERIODS.keys.include?(period)

      @terms          = []
      @starts_on      = (starts_on.is_a?(Date) ? starts_on : Date.parse(starts_on))
      @period         = period
      @starting_index = starting_index

      if interests_start_date
        @interests_start_date = (interests_start_date.is_a?(Date) ? interests_start_date : Date.parse(interests_start_date))
      end
    end

    def <<(term)
      raise ArgumentError.new('LoanCreator::Term expected') unless term.is_a?(LoanCreator::Term)
      term.index  ||= autoincrement_index
      term.due_on ||= date_for(term.index)
      @terms << term
      self
    end

    def to_csv(header: true)
      output = []
      output << terms.first.to_h.keys.join(',') if header
      terms.each { |t| output << t.to_csv }
      output
    end

    def term(index)
      @terms.find { |term| term.index == index }
    end

    private

    def autoincrement_index
      @current_index = (@current_index.nil? ? @starting_index : @current_index + 1)
    end

    def date_for(index)
      @_dates ||= Hash.new do |dates, index|
        dates[index] =
          if index < 1
            dates[index + 1].advance(PERIODS.fetch(period).transform_values {|n| -n})
          elsif index == 1
            starts_on
          else
            dates[index - 1].advance(PERIODS.fetch(period))
          end
      end

      @_dates[index]
    end

    def reset_dates
      @_dates = nil
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
loan_creator-0.8.0 lib/loan_creator/timetable.rb
loan_creator-0.7.1 lib/loan_creator/timetable.rb