ClearPress Framework

Let's say ClearPress doesn't support our favourite format out-of-the-box. YAML for example - pretty common really but it hasn't (yet) been included as a standard response for views. We want to add YAML output using ClearPress' standard method naming (read_yml, list_yml etc.) and tidy file extensions (.yml), just like we do for XML.

First in your view subclass, set any aspects ending in _yml to serve content in text/plain.

sub init {
  my $aspect = $self->aspect;

  $self->{content_type} ||= ($aspect =~ /_yml$/smx)?'text/plain':q[];

  return 1;
}

Next, again in the view subclass, disable page decoration for aspects ending in _yml.

sub decor {
  my $self   = shift;
  my $aspect = $self->aspect;

  if($aspect =~ /_yml$/smx) {
   return 0;
  }
  return $self->SUPER::decor();
}

Set up a template, data/templates/read_something_yml.tt2, to use Template::Plugin::YAML.

[%- USE YAML %]
[% yaml.dump(model) %]
Note that as this stands it will dump the model's data and a lot of other junk from the template engine and the database handle etc.

So far what we've set up will allow us to access URLs like http://example.com/application/something/id;read_yml but that's pretty ugly, so last but not least we want to allow access via clean URLs like http://example.com/application/something/id.yml so in controller.pm we do:

sub accept_extensions {
  my $self = shift;
  return [
          @{$self->SUPER::accept_extensions},
          {'.yml'  => q[_yml]},
         ];
}

Et voila! A YAML-formatted object dump with clean URL formatting. For extra credit you can make a clean data structure to dump using something like this:

[%- USE YAML %]
[%- PERL %]
  $stash->{clean} = {
    map { $_ => $stash->{model}->$_() }
    $stash->{model}->fields()
  }
[% END %]
[%- YAML.dump(clean) %]