class Seniority::AgeCalculator

Attributes

date[R]
error[R]
month[R]
year[R]

Public Class Methods

new(dob) click to toggle source
# File lib/seniority/age_finder.rb, line 3
def initialize(dob)
  # d1 = Date.parse('2018-07-31') -- Date
  # d2 = '31-07-2018'             -- String   -- Date.parse(d2)
  # d3 = Time.now                 -- Time     -- d3.to_date
  @error = ''
  begin
    if dob.class == Date
      dob
    elsif dob.class == String
      dob = Date.parse(dob)
    elsif dob.class == Time
      dob = dob.to_date
    else
      @error = 'Invalid Input!'
    end
  rescue
    @error = 'Invalid Input!'
  end
  if @error != 'Invalid Input!'
    @dob_year, @dob_month, @dob_date = dob.year, dob.month, dob.day
    current_date = Time.now.to_date
    @current_year, @current_month, @current_date = current_date.year, current_date.month, current_date.day
    calculate_date
    calculate_month
    calculate_year
  end
end

Public Instance Methods

borrow_days() click to toggle source
# File lib/seniority/age_finder.rb, line 54
def borrow_days
  if [1, 3, 5, 7, 8, 10, 12].include?(@current_month)
    31
  elsif [4, 6, 9, 11].include?(@current_month)
    30
  elsif [2].include?(@current_month)
    29 if ((@current_year + 1) % 4).zero?
  end
end
calculate_date() click to toggle source
# File lib/seniority/age_finder.rb, line 31
def calculate_date
  if @dob_date > @current_date
    @date = (borrow_days + @current_date) - @dob_date
    @current_month -= 1
  else
    @date = @current_date - @dob_date
  end
end
calculate_month() click to toggle source
# File lib/seniority/age_finder.rb, line 40
def calculate_month
  if @dob_month > @current_month
    @month = (@current_month + 12) - @dob_month # here 12 is borrowed month
    @current_year -= 1 # after taking 12 months borrow we have to
    # reduce 1 year from current year since 1 year = 12 months
  else
    @month = @current_month - @dob_month
  end
end
calculate_year() click to toggle source
# File lib/seniority/age_finder.rb, line 50
def calculate_year
  @year = @current_year - @dob_year
end