ruby implementation for visitor pattern blog post

  • Download Gist
visitor_pattern_implementation_ruby_20081130_blogpost.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
class Employee
attr_reader :name
attr_accessor :sickDaysUsed
attr_accessor :vacationDaysUsed
def initialize(name)
@name = name
@sickDaysUsed = 0
@vacationDaysUsed = 0
end
def addSickDaysUsed(sickDaysUsed)
@sickDaysUsed += sickDaysUsed
end
def addVacationDaysUsed(vacationDaysUsed)
@vacationDaysUsed += vacationDaysUsed
end
end
class HourlyEmployee < Employee
attr_reader :hourlyRate
attr_reader :hoursWorked
def initialize(name, hourlyRate)
super(name)
@hourlyRate = hourlyRate
end
def addHoursWorked(hoursWorked)
@hoursWorked = hoursWorked
end
def accept(visitor)
visitor.HourlyVisit(self)
end
end
class FulltimeEmployee < Employee
attr_reader :salary
attr_accessor :businessDaysWorked
def initialize(name, salary)
super(name)
@salary = salary
end
def addBusinessDaysWorked(businessDaysWorked)
@businessDaysWorked = businessDaysWorked
end
def accept(visitor)
visitor.FulltimeVisit(self)
end
end
class EmployeePaycheckVisitor
attr_reader :earnedWages
attr_reader :sickDayDeductions
attr_reader :paycheckInfo
def HourlyVisit(hourlyEmployee)
name = hourlyEmployee.name
hours = hourlyEmployee.hoursWorked
@sickDayDeductions = hourlyEmployee.sickDaysUsed * 8 * hourlyEmployee.hourlyRate
@earnedWages = hours * hourlyEmployee.hourlyRate @sickDayDeductions
@paycheckInfo = %Q{Hourly employee #{name} worked #{hours} hours, earned
$#{%0.2f % @earnedWages} with #{hourlyEmployee.sickDaysUsed} sick day(s)
($#{%0.2f % @sickDayDeductions} deducted) and
#{hourlyEmployee.vacationDaysUsed} vacation day(s)}
end
def FulltimeVisit(fulltimeEmployee)
name = fulltimeEmployee.name
businessDaysWorked = fulltimeEmployee.businessDaysWorked
dailyRate = (fulltimeEmployee.salary / 52) / 5
@sickDayDeductions = fulltimeEmployee.sickDaysUsed * dailyRate
@earnedWages = businessDaysWorked * dailyRate @sickDayDeductions
@paycheckInfo = %Q{Fulltime employee #{name} worked #{businessDaysWorked}
business days, earned $#{%0.2f % @earnedWages} with
#{fulltimeEmployee.sickDaysUsed} sick day(s) ($#{%0.2f %
@sickDayDeductions} deducted) and #{fulltimeEmployee.vacationDaysUsed}
vacation day(s)}
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.