Subject: | ScalarRef coercion leaves file position at EOF |
Hi,
I'm hoping to use your module to make my class' API more flexible. I was confused when I passed in a ScalarRef and calling getline on the resulting IO object returned undef.
I'm not sure why the ScalarRef coercion works the way it does, not being familiar with IO::All and its subclasses. My first attempt to fix this made the coercion just return io($_), however then it failed the "get string" test.
I have found that a seek call to return the file position to the start of the string-backed file gives us the best of both worlds; its still a IO::All::String and it responds to getline as though io($_) were used.
See attached for the patch, thanks for your excellent module.
Cheers,
Andrew Kirkpatrick
Subject: | MooseX-Types-IO-ScalarRef.patch |
diff -ru MooseX-Types-IO-0.03-orig/lib/MooseX/Types/IO/All.pm MooseX-Types-IO-0.03/lib/MooseX/Types/IO/All.pm
--- MooseX-Types-IO-0.03-orig/lib/MooseX/Types/IO/All.pm 2009-05-19 08:14:52.000000000 +0930
+++ MooseX-Types-IO-0.03/lib/MooseX/Types/IO/All.pm 2014-04-03 00:43:44.135750229 +1030
@@ -11,6 +11,7 @@
use MooseX::Types::Moose qw/Str ScalarRef FileHandle ArrayRef/;
use namespace::clean;
use MooseX::Types -declare => [qw( IO_All )];
+use Fcntl 'SEEK_SET';
my $global = class_type 'IO::All';
subtype IO_All, as 'IO::All';
@@ -24,6 +25,7 @@
via {
my $s = io('$');
$s->print($$_);
+ $s->seek(0, SEEK_SET);
return $s;
};
diff -ru MooseX-Types-IO-0.03-orig/t/02-io-all.t MooseX-Types-IO-0.03/t/02-io-all.t
--- MooseX-Types-IO-0.03-orig/t/02-io-all.t 2009-05-19 08:14:52.000000000 +0930
+++ MooseX-Types-IO-0.03/t/02-io-all.t 2014-04-03 00:43:03.395750687 +1030
@@ -1,6 +1,6 @@
#!perl -T
-use Test::More tests => 16;
+use Test::More tests => 22;
use Test::Exception;
use MooseX::Types::IO::All 'IO_All';
@@ -32,12 +32,19 @@
for my $accessor (qw/io io2/) {
my $str = "test for IO::All\n line 2";
+
+ # split on the empty string after newlines
+ my @lines = split /(?<=\n)/, $str;
+
my $coerced = Foo->new( $accessor => \$str )->$accessor;
isa_ok( $coerced, "IO::All", "coerced IO::All" );
ok( $coerced->can('print'), "can print" );
is( ${ $coerced->string_ref }, $str, 'get string');
-
+ is( $coerced->getline, $lines[0], 'getline 1');
+ is( $coerced->getline, $lines[1], 'getline 2');
+ is( $coerced->getline, undef, 'getline eof');
+
my $filename = "$Bin/00-load.t";
my $str2 = <<'FC';
#!perl -T