Saturday, December 4, 2010

Day 4: inheritable DATA sections with Data::Section

Damn, RJBS beat me on Sub::Exporter / Sub::Import! I wanted to write about them too. But he was faster. Maybe this time, I am faster. :)

Today I want to show you Data::Section, which is (like Sub::Exporter and Sub::Import) from Ricardo Signes. It has two use cases (and I will show an example for both):
  • inheritable DATA sections
  • multiple 'files' (hunks) in the DATA section
Consider the following modules:
# file: Parent.pm
package Parent;
use Data::Section -setup => {default_name => 'default'};
1;
__DATA__
__[file1]__
Master version of file 1.
__[file2]__
Master version of file 2.

# file: Child.pm
package Child;
use base 'Parent';
1;
__DATA__
Default name content.
__[file1]__
Custom version of file 1.

Now you can use Data::Section's methods for retrieval on these modules:
use Child;
use Data::Dump;
print ${Child->section_data('file1')};
print dd(Child->merged_section_data);

Each data section is returned as scalar reference. The output is the following:
Custom version of file 1.
{
  default => \"Default name content.\n",
  file1   => \"Custom version of file 1.\n",
  file2   => \"Master version of file 2.\n",
}

I used Data::Section in my experimental web framework UVWeb for inheritable templates in CRUD actions. I stopped working on UVWeb and switched all my projects to Catalyst. But this was a feature I especially liked.

Have a look at Mojo::Command (and Mojolicious::Command::Generate::App) for another approach and an example use case.

Links:

1 comment:

  1. Thanks!

    http://advent.rjbs.manxome.org/2009/2009-12-09.html :-)

    ReplyDelete

Note: Only a member of this blog may post a comment.