Permalink
Browse files

implement model_dir(), glob(), all() for models

rewrite save(), and path()
  • Loading branch information...
1 parent 38b5c2d commit 5165c65d69264e3c49bc8d69748a6ae9780ee1c1 @shelling committed Jan 14, 2013
Showing with 93 additions and 9 deletions.
  1. +93 −9 lib/HTTP/Balancer/Model.pm
@@ -3,35 +3,119 @@ use Modern::Perl;
use Moose;
use File::Spec;
+=head1 NAME
+
+HTTP::Balancer::Model - the base class of models of HTTP::Balancer
+
+=head1 SYNOPSIS
+
+ package HTTP::Balancer::Model::Foo;
+ use Modern::Perl;
+ use Moose;
+ extends qw(HTTP::Balancer::Model);
+
+=cut
+
our $dbpath = "/tmp/";
+=head1 FUNCTIONS AND METHODS
+
+=head2 model_name
+
+class method and instance method
+
+returns lowercase of last name of current model
+
+=cut
+
sub model_name {
my ($self, ) = @_;
- my $ref = ref($self);
+ my $ref = ref($self) || $self;
$ref =~ s{HTTP::Balancer::Model::}{};
return lc($ref);
}
+=head2 model_dir
+
+class method and instance method
+
+returns the directory store the entities of current model
+
+=cut
+
+sub model_dir {
+ my ($self, ) = @_;
+ File::Spec->catdir(
+ $dbpath,
+ $self->model_name
+ );
+}
+
+=head2 path
+
+instance method
+
+returns the path for storing current object
+
+=cut
+
sub path {
my ($self, ) = @_;
File::Spec->catfile(
- $dbpath,
- $self->model_name,
+ $self->model_dir,
$self->id
);
}
+=head2 glob
+
+class method
+
+returns all entities stored in model_dir, sorted with id.
+
+=cut
+
+sub glob {
+ my ($self, ) = @_;
+ sort {
+ pop [File::Spec->splitpath($a)] <=> pop [File::Spec->splitpath($b)]
+ }
+ glob(File::Spec->catfile($self->model_dir, "*"));
+}
+
+=head2 save
+
+instance method
+
+save current object into model_dir, named as its id.
+
+generate auto-incremented id for new object not on disk yet.
+
+=cut
+
sub save {
my ($self, ) = @_;
- my @glob = glob($self->path . "*");
- my ($vol, $dir, $num) = File::Spec->splitpath(
- [@glob]->[-1]
- ) if scalar @glob;
- $num //= 0;
+ unless ($self->id) {
+ my $last = pop [$self->glob];
+ my $num = $last ? pop [File::Spec->splitpath($last)] : 0;
+ $self->id($num+1)
+ }
- $self->id($num+1) unless $self->id;
$self->store($self->path);
}
+=head2 all
+
+class method
+
+returns all object restored from disk
+
+=cut
+
+sub all {
+ my ($self, ) = @_;
+ map { $self->load($_) } $self->glob;
+}
+
1;

0 comments on commit 5165c65

Please sign in to comment.