Skip to content

Commit

Permalink
should also keep adding new brands to the brands list
Browse files Browse the repository at this point in the history
  • Loading branch information
tijs committed Nov 25, 2024
1 parent 4bbf8d6 commit 9cc67ca
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
30 changes: 26 additions & 4 deletions lib/vehicle_creator/data_store.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,26 @@ class DataStore
def initialize(file_path)
@file_path = file_path
@data = load_data
@data["brands"] ||= []
end

def save_vehicle(vehicle_data)
@data["data"] << vehicle_data

unless brand_exists?(vehicle_data["brand"])
@data["brands"] << {
"id" => vehicle_data["brand_id"],
"name" => vehicle_data["brand"]
}
@data["brands"].sort_by! { |b| b["name"] }
end

update_meta
write_to_file
end

def existing_brands
@data["data"].map { |v| v["brand"] }.uniq.sort
@data["brands"].map { |b| b["name"] }
end

def existing_models(brand)
Expand All @@ -23,14 +33,26 @@ def existing_models(brand)
end

def find_or_create_brand_id(brand)
existing = @data["data"].find { |v| v["brand"] == brand }
existing ? existing["brand_id"] : SecureRandom.uuid
existing = @data["brands"].find { |b| b["name"] == brand }
if existing
existing["id"]
else
SecureRandom.uuid
end
end

private

def brand_exists?(brand_name)
@data["brands"].any? { |b| b["name"] == brand_name }
end

def load_data
JSON.parse(File.read(@file_path))
data = JSON.parse(File.read(@file_path))
data["brands"] ||= []
data["data"] ||= []
data["meta"] ||= {}
data
end

def update_meta
Expand Down
6 changes: 6 additions & 0 deletions test/vehicle_creator_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@ def setup
"vehicle_type" => "car",
"brand_id" => "test-brand-id-1"
}
],
"brands" => [
{
"id" => "test-brand-id-1",
"name" => "Test Brand"
}
]
}

Expand Down

0 comments on commit 9cc67ca

Please sign in to comment.