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:
package Parent;
use Data::Section -setup => {default_name => 'default'};
Master version of file 1.
Master version of file 2.

# file:
package Child;
use base 'Parent';
Default name content.
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.


1 comment:

  1. Thanks! :-)