File Coverage: lib/Yukki/Role/Savable.pm

# File Coverage

File: | lib/Yukki/Role/Savable.pm
Coverage: | 64.1%

line | stmt | bran | cond | sub | pod | time | code
--- | --- | --- | --- | --- | --- | --- | ---
1 |  |  |  |  |  |  | package Yukki::Role::Savable;
2 |
3 | 4 4 |  |  | 4 |  | 14275 11 | use v5.24;
4 | 4 4 4 |  |  | 4 |  | 13 19 18 | use utf8;
5 | 4 4 4 |  |  | 4 |  | 53 5 19 | use Moo::Role;
6 |
7 | 4 4 4 |  |  | 4 |  | 1022 5 155 | use Scalar::Util qw( blessed );
8 | 4 4 4 |  |  | 4 |  | 1425 11385 450 | use YAML qw( Dump Load );
9 |
10 |  |  |  |  |  |  | # ABSTRACT: Provides a mechanism for YAML-izing objects
11 |
12 - 44 |  |
    =head1 SYNOPSIS

        package Yukki::Things;
        use v5.24;
        use Moo;

        with 'Yukki::Role::Savable';

        has foo => ( is => 'ro' );
        has bar => ( is => 'ro' );

        sub savable_attributes { qw( foo bar ) }

        my $things = Yukki::Things->new(foo => 1, bar => 2);
        path('file.yaml')->spew_utf8($things->dump_yaml);

        my $things = Yukki::Things->load_yaml(path('file.yaml')->slurp_utf8);
        say $things->foo; #> 1
        say $things->bar; #> 2

    =head1 DESCRIPTION

    This is intended to provide L<Yukki> with a nice, neat way to save and load some configuration objects in a standard way.

    =head1 REQUIRED METHODS

    =head2 savable_attributes

        my @attr = $obj->savable_attributes;

    Returns the list of attributes to save in the YAML.

    =cut
45 |
46 |  |  |  |  |  |  | requires 'savable_attributes';
47 |
48 - 56 |  |
    =head1 METHODS

    =head2 dump_yaml

        my $yaml_text = $obj->dump_yaml;

    This converts the object to YAML and returns the ext.

    =cut
57 |
58 |  |  |  |  |  |  | sub dump_yaml {
59 | 0 |  |  | 0 | 1 | 0 | my $self = shift;
60 |
61 | 0 |  |  |  |  | 0 | my %output;
62 | 0 |  |  |  |  | 0 | for my $attr ($self->savable_attributes) {
63 | 0 |  |  |  |  | 0 | my $v = $self->$attr;
64 | 0 | 0 | 0 |  |  | 0 | if (blessed $v && $v->does('Yukki::Role::Savable')) {
65 | 0 |  |  |  |  | 0 | $v = $v->dump_yaml;
66 |  |  |  |  |  |  | }
67 | 0 |  |  |  |  | 0 | $output{ $attr } = $v;
68 |  |  |  |  |  |  | }
69 |
70 | 0 |  |  |  |  | 0 | return Dump(\%output);
71 |  |  |  |  |  |  | }
72 |
73 - 79 |  |
    =head2 load_yaml

        my $obj = $class->load_yaml($yaml_text);

    This constructs a new class from the data loaded from the given YAML text.

    =cut
80 |
81 |  |  |  |  |  |  | sub load_yaml {
82 | 1 |  |  | 1 | 1 | 138 | my ($class, $yaml) = @_;
83 |
84 | 1 |  |  |  |  | 5 | my $input = Load($yaml);
85 | 1 |  |  |  |  | 2510 | $class->new($input);
86 |  |  |  |  |  |  | }
87 |
88 |  |  |  |  |  |  | 1;