From 6031f2d68c1681043cfe0d027bb6f0e6278f48d0 Mon Sep 17 00:00:00 2001 From: Vasily Kolesnikov Date: Fri, 3 Nov 2017 18:44:29 +0300 Subject: [PATCH] Allow to provide options for CSV loading --- lib/rom/csv/gateway.rb | 18 +++++++------- spec/fixtures/semicolon.csv | 3 +++ spec/integration/setup/csv_options_spec.rb | 28 ++++++++++++++++++++++ 3 files changed, 40 insertions(+), 9 deletions(-) create mode 100644 spec/fixtures/semicolon.csv create mode 100644 spec/integration/setup/csv_options_spec.rb diff --git a/lib/rom/csv/gateway.rb b/lib/rom/csv/gateway.rb index 446fa2b..d6a71fa 100644 --- a/lib/rom/csv/gateway.rb +++ b/lib/rom/csv/gateway.rb @@ -46,27 +46,27 @@ class Gateway < ROM::Gateway # @return [Gateway] # # @api public - def self.new(path, *) - super(load_from(path)) + def self.new(path, options = {}) + super(load_from(path, options)) end # Load data from CSV file(s) # # @api private - def self.load_from(path) + def self.load_from(path, options = {}) if File.directory?(path) - load_files(path) + load_files(path, options) else - { source_name(path) => load_file(path) } + { source_name(path) => load_file(path, options) } end end # Load CSV files from a given directory and return a name => data map # # @api private - def self.load_files(path) + def self.load_files(path, options = {}) Dir["#{path}/*.csv"].each_with_object({}) do |file, h| - h[source_name(file)] = load_file(file) + h[source_name(file)] = load_file(file, options) end end @@ -77,8 +77,8 @@ def self.source_name(filename) # Load CSV file # # @api private - def self.load_file(path) - ::CSV.table(path).map(&:to_h) + def self.load_file(path, options = {}) + ::CSV.table(path, options).map(&:to_h) end # @api private diff --git a/spec/fixtures/semicolon.csv b/spec/fixtures/semicolon.csv new file mode 100644 index 0000000..bdff0b8 --- /dev/null +++ b/spec/fixtures/semicolon.csv @@ -0,0 +1,3 @@ +user_id;name;email +1;Jane;jane@doe.org +2;John;john@doe.org diff --git a/spec/integration/setup/csv_options_spec.rb b/spec/integration/setup/csv_options_spec.rb new file mode 100644 index 0000000..bb693cc --- /dev/null +++ b/spec/integration/setup/csv_options_spec.rb @@ -0,0 +1,28 @@ +require 'spec_helper' + +RSpec.describe ROM::CSV do + let(:configuration) do + ROM::Configuration.new(:csv, uri, csv_options) + end + + let(:rom) { ROM.container(configuration) } + + context 'when CSV options provided' do + let(:uri) { File.expand_path('./spec/fixtures/semicolon.csv') } + let(:csv_options) { { col_sep: ';' } } + + before do + configuration.relation(:users) do + schema(:semicolon) do + end + end + end + + it 'uses csv options for load data' do + expect(rom.relations[:users].to_a).to eql [ + { user_id: 1, name: "Jane", email: "jane@doe.org" }, + { user_id: 2, name: "John", email: "john@doe.org" } + ] + end + end +end