fix the CSV source to accept input from a file handle
authorTony Cook <tony@develop-help.com>
Fri, 5 Apr 2013 10:17:37 +0000 (21:17 +1100)
committerTony Cook <tony@develop-help.com>
Mon, 8 Apr 2013 00:54:35 +0000 (10:54 +1000)
This fixes it for use from the web UI

site/cgi-bin/modules/BSE/Importer/Source/CSV.pm
t/130-importer/010-csv.t

index 4b715d5bf53465c740b8fa2b10752e5f7b73a680..cd8babe3cc6bc726b2fed3947a87db19a473140c 100644 (file)
@@ -3,7 +3,7 @@ use strict;
 use base 'BSE::Importer::Source::Base';
 use Text::CSV;
 
-our $VERSION = "1.000";
+our $VERSION = "1.001";
 
 my @text_csv_options = qw(quote_char escape_char sep_char binary allow_loose_quotes allow_loose_escapes allow_whitespace);
 
@@ -112,8 +112,16 @@ sub new {
 sub each_row {
   my ($self, $importer, $filename) = @_;
 
-  open my $fh, "<encoding($self->{encoding})", $filename
-    or die "Cannot open file $filename: $!\n";
+  my $fh;
+
+  if (ref $filename) {
+    $fh = $filename;
+    binmode $fh, ":encoding($self->{encoding})";
+  }
+  else {
+    open $fh, "<:encoding($self->{encoding})", $filename
+      or die "Cannot open file $filename: $!\n";
+  }
 
   my $csv = Text::CSV->new($self->{csv_opts})
     or die "Cannot use CSV: ", Text::CSV->error_diag(), "\n";
index 4175117b16f5a9d03c8f5bd203fc7eac37f09950..b5d0ea420dc9c12df7e5f521dcc07848e1bb2644 100644 (file)
@@ -1,6 +1,6 @@
 #!perl -w
 use strict;
-use Test::More tests => 6;
+use Test::More tests => 8;
 use BSE::Cfg;
 BEGIN {
   eval "require Text::CSV;"
@@ -29,6 +29,34 @@ CFG
       ], "check data read");
 }
 
+{
+  my $cfg = BSE::Cfg->new_from_text(text => <<CFG);
+[import profile test]
+source=CSV
+CFG
+  my $importer = DummyImporter->new(columns => 3, cfg => $cfg);
+  my $src = BSE::Importer::Source::CSV->new
+    (
+     importer => $importer,
+     opts => { profile => "test", cfg => $cfg },
+    );
+  ok($src, "make a CSV source");
+
+  my $csv = <<EOS;
+a,b,c
+1,2,3
+abc,def,hij
+EOS
+  open my $fh, "<", \$csv;
+
+  $src->each_row($importer, $fh);
+  is_deeply($importer->{rows},
+      [
+       [ "Line 2", 1, 2, 3 ],
+       [ "Line 3", qw(abc def hij) ],
+      ], "check data read with fh source");
+}
+
 {
   my $cfg = BSE::Cfg->new_from_text(text => <<'CFG');
 [import profile test]