Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support csv backend #32

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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