Created
October 20, 2020 17:49
-
-
Save Haumer/de5fdc0d83826bbaaff2168496879312 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 BaseRepo | |
def initialize(csv_file) | |
@csv_file = csv_file | |
@elements = [] | |
@next_id = 1 | |
load_csv if File.exist?(@csv_file) | |
end | |
def create(element) | |
element.id = @next_id | |
@elements << element | |
@next_id += 1 | |
save_csv | |
end | |
def all | |
@elements | |
end | |
def find(id) | |
@elements.find { |element| element.id == id } | |
end | |
def save_csv | |
CSV.open(@csv_file, "wb") do |csv| | |
csv << @elements.first.class.headers | |
@elements.each do |element| | |
csv << write_to_csv_row(element) | |
end | |
end | |
end | |
def load_csv | |
options = { headers: :first_row, header_converters: :symbol } | |
CSV.foreach(@csv_file, options) do |row| | |
build_csv_row(row) | |
@next_id = row[:id] | |
end | |
@next_id = @elements.empty? ? 1 : @elements.last.id + 1 | |
end | |
end |
This file contains hidden or 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
require_relative "base_repo" | |
require_relative "../models/customer" | |
class CustomerRepository < BaseRepo | |
def write_to_csv_row(element) | |
[element.id, element.name, element.address] | |
end | |
def build_csv_row(row) | |
row[:id] = row[:id].to_i | |
@elements << Customer.new(row) | |
end | |
end |
This file contains hidden or 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
require_relative "base_repo" | |
require_relative "../models/meal" | |
class MealRepo < BaseRepo | |
def write_to_csv_row(element) | |
[element.id, element.name, element.price] | |
end | |
def build_csv_row(row) | |
row[:id] = row[:id].to_i | |
row[:price] = row[:price].to_i | |
@elements << Meal.new(row) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment