Skip to content

Instantly share code, notes, and snippets.

@oddlyfunctional
Created July 11, 2017 14:19
Show Gist options
  • Save oddlyfunctional/50977c186bad8a4493ab44399b2ad86c to your computer and use it in GitHub Desktop.
Save oddlyfunctional/50977c186bad8a4493ab44399b2ad86c to your computer and use it in GitHub Desktop.
Modeling data with associations
require_relative "patients_repository"
require_relative "rooms_repository"
require_relative "room"
require 'csv'
rooms_repository = RoomsRepository.new("rooms.csv")
patient_repository = PatientsRepository.new("patients.csv", rooms_repository)
room = Room.new(capacity: 10)
rooms_repository.add(room)
another_room = Room.new(capacity: 6)
rooms_repository.add(another_room)
p patient_repository.all
class Patient
def initialize(attributes = {})
@name = attributes[:name]
@discharged = attributes[:discharged] || false
@room = attributes[:room]
end
def room=(room)
@room = room
end
def name
@name
end
end
name discharged room_id
John false 1
Paul false 1
require_relative "patient"
class PatientsRepository
def initialize(csv_file_path, rooms_repository)
@csv_file_path = csv_file_path
@rooms_repository = rooms_repository
@patients = []
load_csv
end
def all
@patients
end
def add(patient)
@patients << patient
save_csv
end
def load_csv
options = { headers: :first_row, header_converters: :symbol }
CSV.foreach("patients.csv", options) do |row|
patient = Patient.new(row)
room_id = row[:room_id].to_i
room = @rooms_repository.all.find { |room| room.id == room_id }
patient.room = room
room.add_patient(patient)
@patients << patient
end
end
end
class Room
class RoomFullError < Exception
end
attr_accessor :id
attr_reader :capacity
def initialize(attributes = {})
@capacity = attributes[:capacity]
@patients = attributes[:patients] || []
end
def full?
@capacity <= @patients.size
end
def add_patient(patient)
if full?
fail RoomFullError, "Room is full!"
else
@patients << patient
end
end
end
id capacity
1 2
3 4
require_relative "room"
class RoomsRepository
def initialize(csv_file_path)
@csv_file_path = csv_file_path
@rooms = []
load_csv
@next_id = all.last.id + 1
end
def all
@rooms
end
def add(room)
room.id = @next_id
@rooms << room
save_csv
@next_id += 1
end
def load_csv
options = { headers: :first_row, header_converters: :symbol }
CSV.foreach(@csv_file_path, options) do |row|
row[:capacity] = row[:capacity].to_i
room = Room.new(row)
room.id = row[:id].to_i
@rooms << room
end
end
def save_csv
CSV.open(@csv_file_path, "wb") do |csv|
csv << ["id", "capacity"]
all.each do |room|
p room.capacity
csv << [room.id, room.capacity]
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment