Created
July 23, 2015 15:44
-
-
Save joshnesbitt/fd6999fb0c4601c0d16b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Company | |
TooManyManagingDirectorsError = Class.new(Exception) | |
class Department | |
attr_reader :company, | |
:name, | |
:employees | |
def initialize(company, name, &block) | |
@company = company | |
@name = name | |
@employees = [] | |
instance_eval(&block) | |
end | |
def employee(&block) | |
@employees << Employee.new(self, &block) | |
end | |
end | |
class Employee | |
attr_reader :deparment | |
def initialize(deparment, &block) | |
@deparment = deparment | |
instance_eval(&block) | |
end | |
def managing_director | |
if @deparment.company.managing_director.nil? | |
@managing_director = true | |
else | |
raise TooManyManagingDirectorsError | |
end | |
end | |
def managing_director? | |
!!@managing_director | |
end | |
%w( first_name last_name role ).each do |method| | |
define_method method do |*args| | |
attribute = "@#{method}" | |
if args.empty? | |
self.instance_variable_get(attribute) | |
else | |
self.instance_variable_set(attribute, args.first) | |
end | |
end | |
end | |
end | |
attr_reader :departments | |
def initialize(&block) | |
@departments = [] | |
instance_eval(&block) | |
end | |
def department(name, &block) | |
departments << Department.new(self, name, &block) | |
end | |
def employees | |
departments.map do |department| | |
department.employees | |
end.flatten | |
end | |
def managing_director | |
employees.select { |e| e.managing_director? }.first | |
end | |
end | |
def company(&block) | |
if block_given? | |
@company = Company.new(&block) | |
else | |
@company | |
end | |
end | |
require_relative 'run' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment