Skip to content

Instantly share code, notes, and snippets.

@vanakenm
Created March 1, 2016 10:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vanakenm/b8bb66f27847e10b2554 to your computer and use it in GitHub Desktop.
Save vanakenm/b8bb66f27847e10b2554 to your computer and use it in GitHub Desktop.
class Patient
attr_reader :name, :cured, :id
attr_accessor :room
def initialize(attributes)
@name = attributes[:name]
@id = attributes[:id].to_i
@cured = attributes[:cured] || false
end
def cure
@cured = true
end
end
id name cured room_id
1 Bob false 1
2 Alan false 1
require 'csv'
require_relative 'patient'
require_relative 'rooms_repository'
class PatientsRepository
def initialize(csv_file, rooms_repository)
@rooms_repository = rooms_repository
@csv_file = csv_file
@patients = []
load_csv
end
def all
@patients
end
def load_csv
CSV.foreach(@csv_file, headers: true, header_converters: :symbol) do |row|
patient = Patient.new(row)
room_id = row[:room_id].to_i
room = @rooms_repository.find(room_id)
room.add_patient(patient)
@patients << patient
end
end
end
rooms_repo = RoomsRepository.new(File.join(__dir__, 'rooms.csv'))
patients_repo = PatientsRepository.new(File.join(__dir__,'patients.csv'), rooms_repo)
bob = patients_repo.all.first
p bob.name
p bob.room.name
p bob.room.patients.map(&:name)
require_relative 'patient'
class Room
attr_reader :size, :name, :patients
attr_accessor :id
def initialize(attributes)
@size = attributes[:size].to_i
@name = attributes[:name]
@id = attributes[:id].to_i
@patients = []
end
def add_patient(patient)
@patients << patient
patient.room = self
end
end
id name size
1 2a 3
2 3z 12
require 'csv'
require_relative 'room'
class RoomsRepository
def initialize(csv_file)
@csv_file = csv_file
@rooms = []
load_csv
end
def find(id)
@rooms.find { |r| r.id == id }
end
def all
@rooms
end
def load_csv
@next_id = 0
CSV.foreach(@csv_file, headers: true, header_converters: :symbol) do |row|
@rooms << Room.new(row)
@next_id += 1
end
end
def save(room)
room.id = @next_id + 1
@rooms << room
CSV.open(@csv_file, 'wb') do |csv|
csv << ['id', 'name', 'size']
@rooms.each do |room|
csv << [room.id, room.name, room.size]
end
end
end
end
# room = Room.new(name: '3z', size: 12)
# repo.save(room)
# p repo.all
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment