Sunday, March 20, 2011

Serving the right file suffix

Sometimes if you use applications other than the browser to open up links (i.e.: Excel), they behave better if the file served has the neat, correct suffix at the end.
This messes up all internal paths in Catalyst though. So I figured out that if I could clean up the suffix at the end of the URI, and keep it as the format parameter, I'd solved the problem. So here's the code:



# inside My::Catalyst::App

after 'prepare_path' => sub {
my ($c) = @_;
local $_ = $c->request->path;
s/\.([a-z]+)$//i;
$c->stash->{format} = lc $1 || 'html';
$c->request->path($_);
};

Cleaning up parameters

I decided that one-letter parameters would be only for internal application use, so that all other can be directly used for querying data. That way I can separate them out before every action, by using a private action in the root controller like this:

sub begin : Private {
my ( $self, $c) = @_;
my ($p, $i);
$p = $c->req->params;
for (grep { /^\w$/ } keys %{$p}) {
$i->{$_} = $p->{$_};
delete $p->{$_}
}

$c->stash->{params} = $p;
$c->stash->{int_params} = $i;
}

Now I have a set of separate parameters that I can use

  • v = view
  • f = format
  • q = query
  • p = page
  • n = number per page
  • s = sort
  • c = columns
  • l = language