Created
November 4, 2009 10:22
-
-
Save deppp/225951 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package App::Role::Storage; | |
use MooseX::Role::Parameterized; | |
use Moose::Util::TypeConstraints; | |
use Class::MOP; | |
my %mapping = ( | |
YAML => [qw/Dump Load/], | |
JSON => [qw/to_json from_json/], | |
Storable => [qw/freeze thaw/] | |
); | |
parameter 'type' => ( | |
isa => (enum ['Storable', 'YAML', 'JSON']), | |
default => 'Storable', | |
); | |
role { | |
no strict 'refs'; # use common::sense :) | |
my $p = shift; | |
my $type = $p->type; | |
Class::MOP::load_class($type); | |
# get method name we actually want to use | |
my $freeze = $type . '::' . $mapping{$type}->[0]; | |
my $thaw = $type . '::' . $mapping{$type}->[1]; | |
method 'freeze' => sub { | |
my $self = shift; | |
&{$freeze}(@_); | |
}; | |
method 'thaw' => sub { | |
my $self = shift; | |
&{$thaw}(@_); | |
}; | |
}; | |
package App; | |
use Moose; | |
with 'App::Role::Storage' => { type => 'JSON' }; | |
has 'data' => ( isa => 'ArrayRef[Str]', is => 'rw' ); | |
package main; | |
use Data::Dump 'dump'; | |
my $app = App->new(data => [qw/some lines with data/]); | |
my $data = $app->freeze($app->data); | |
my $orig = $app->thaw($data); | |
dump $data; | |
dump $orig; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment