From: Sven Schöling Date: Wed, 8 Aug 2012 15:58:45 +0000 (+0200) Subject: SL::SessionFile::Random - damit man sich nicht selber einen Namen ausdenken muss X-Git-Tag: release-3.0.0beta1~297^2~16 X-Git-Url: http://wagnertech.de/git?a=commitdiff_plain;h=4fc07be473b8e80e5c808d2876762383f660aa25;p=kivitendo-erp.git SL::SessionFile::Random - damit man sich nicht selber einen Namen ausdenken muss --- diff --git a/SL/SessionFile.pm b/SL/SessionFile.pm index 69997e9a1..6f04041e1 100644 --- a/SL/SessionFile.pm +++ b/SL/SessionFile.pm @@ -24,6 +24,8 @@ sub new { $file_name =~ s:.*/::g; $file_name = "${path}/${file_name}"; + $self->file_name($file_name); + if ($params{mode}) { my $mode = $params{mode}; @@ -35,11 +37,14 @@ sub new { $self->fh(IO::File->new($file_name, $mode)); } - $self->file_name($file_name); - return $self; } +sub open { + my ($self, $mode) = @_; + return $self->fh(IO::File->new($self->file_name, $mode)); +} + sub exists { my ($self) = @_; return -f $self->file_name; @@ -139,6 +144,10 @@ Returns the full relative file name associated with this instance. If it has been created for "customer.csv" then the value returned might be C. +=item C + +Opens the file_name given at creation with the given parameters. + =item C Returns trueish if the file exists. diff --git a/SL/SessionFile/Random.pm b/SL/SessionFile/Random.pm new file mode 100644 index 000000000..366baf439 --- /dev/null +++ b/SL/SessionFile/Random.pm @@ -0,0 +1,62 @@ +package SL::SessionFile::Random; + +use strict; +use parent qw(SL::SessionFile); + +my @CHARS = ('A'..'Z', 'a'..'z', 0..9, '_'); +my $template = 'X' x 10; +use constant MAX_TRIES => 1000; + +sub new { + my ($class, %params) = @_; + + my $filename; + my $tries = 0; + $filename = _get_file() while $tries++ < MAX_TRIES && (!$filename || -e $filename); + + $class->SUPER::new($filename, %params); +} + +sub _get_file { + my $filename = $template; + $filename =~ s/X(?=X*\z)/$CHARS[ int( rand( @CHARS ) ) ]/ge; + $filename; +} + +1; + +__END__ + +=encoding utf-8 + +=head1 NAME + +SL::SessionFile::Random - SessionFile with a random name + +=head1 SYNOPSIS + + use SL::SessionFile::Random; + + # Create a session file named "customer.csv" (relative names only) + my $sfile = SL::SessionFile::Random->new("w"); + $sfile->fh->print("col1;col2;col3\n" . + "value1;value2;value3\n"); + $sfile->fh->close; + +=head1 DESCRIPTION + +This modules gives you a random file in the current session cache that is guaranteed to be unique + +=head1 FUNCTIONS + +same as SL::SessioNFile + +=head1 BUGS + +NONE yet. + +=head1 AUTHOR + +Sven Schoeling Es.schoeling@linet-services.deE + +=cut