Skip to content

Commit

Permalink
support csv backend
Browse files Browse the repository at this point in the history
  • Loading branch information
mollerhoj committed Apr 19, 2020
1 parent f35bb22 commit 4bcbde5
Show file tree
Hide file tree
Showing 5 changed files with 33 additions and 1 deletion.
1 change: 1 addition & 0 deletions lib/frozen_record/backends.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,6 @@ module FrozenRecord
module Backends
autoload :Json, 'frozen_record/backends/json'
autoload :Yaml, 'frozen_record/backends/yaml'
autoload :Csv, 'frozen_record/backends/csv'
end
end
21 changes: 21 additions & 0 deletions lib/frozen_record/backends/csv.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# frozen_string_literal: true
require 'csv'

module FrozenRecord
module Backends
module Csv
extend self

def filename(model_name)
"#{model_name.underscore.pluralize}.csv"
end

def load(file_path)
csv_data = File.read(file_path)
CSV.parse(csv_data, headers: true, nil_value: '').map.with_index do |row, index|
row.to_h.merge("position" => index)
end
end
end
end
end
3 changes: 3 additions & 0 deletions spec/fixtures/employees.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
"name","title"
"john doe","Engineer"
"tom doe","Manager"
6 changes: 5 additions & 1 deletion spec/frozen_record_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -118,11 +118,15 @@
expect(country.capital).to be == 'Ottawa'
end

it 'loads records with a custom backend' do
it 'loads records with a custom backend json' do
animal = Animal.first
expect(animal.name).to be == 'cat'
end

it 'loads records with a custom backend csv' do
employee = Employee.first
expect(employee.name).to be == 'john doe'
end
end

describe '#==' do
Expand Down
3 changes: 3 additions & 0 deletions spec/support/employee.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
class Employee < FrozenRecord::Base
self.backend = FrozenRecord::Backends::Csv
end

0 comments on commit 4bcbde5

Please sign in to comment.