Skip to content

Instantly share code, notes, and snippets.

@marcoarthur
Created July 23, 2023 13:43
Show Gist options
  • Save marcoarthur/7ada2c07dc5ae1394e4948515296c965 to your computer and use it in GitHub Desktop.
Save marcoarthur/7ada2c07dc5ae1394e4948515296c965 to your computer and use it in GitHub Desktop.
Object::Pad role composition
use v5.26;
use Object::Pad;
role GitRole {
use Git::Wrapper;
use Carp qw(carp croak);
use Syntax::Keyword::Try;
field $repo :reader = undef;
method repo_init {
return $repo if $repo;
my $path = $self->path;
$path->mkdir unless $path->exists;
try {
$repo = Git::Wrapper->new($path);
$repo->status;
} catch ($e) {
carp "initializing a new repo";
qx{ cd $path && git init };
$repo = Git::Wrapper->new($path);
}
croak "Could not initialize a repo in $path" unless $repo->status;
return $repo;
}
1;
}
class GitPath :does(GitRole) {
use Path::Tiny;
use overload
'""' => sub { shift->path };
field $path :param :reader;
ADJUST {
$path = Path::Tiny::path($path); # make path a Path::Tiny
$self->repo_init; # install repo as Git::Wrapper
}
1;
}
use Test::More;
my $path = '/tmp/new';
my $gp = GitPath->new( path => $path );
ok $gp, 'created a git repo';
is $gp->path, $path, 'stringnified ok';
isa_ok $gp->repo, 'Git::Wrapper', 'Is the right thing';
undef $gp;
done_testing;
__END__
=pod
=head1 Example
This is a small example about Object::Pad to remember the compounding with Roles
as well as with the use of overloading (in this case a stringfy operation).
=head2 Roles
Role is a great way to make functionality of object to be more horizontal in
between wide range of classes (aliviating inheritance as the only way to
extend functionality). In this example we make a GitRole that actually install
a member (slot) to the class that provides a "path" member, a Git::Wrapper handle
to "path".
=cut
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment