Skip to content

Instantly share code, notes, and snippets.

@leedo
Created March 24, 2010 01:09
Show Gist options
  • Save leedo/341870 to your computer and use it in GitHub Desktop.
Save leedo/341870 to your computer and use it in GitHub Desktop.
package Plack::Middleware::Sprockets;
use strict;
use 5.008_001;
our $VERSION = '0.01';
use JavaScript::Sprockets;
use Plack::Util::Accessor qw(sprockets load_paths root);
use Plack::Util;
use base 'Plack::Middleware';
sub prepare_app {
my $self = shift;
my $sp = JavaScript::Sprockets->new;
$sp->root($self->root) if $self->root;
$sp->load_paths($self->load_paths) if $self->load_paths;
$self->sprockets($sp);
}
sub call {
my ($self, $env) = @_;
my $orig_path = $env->{PATH_INFO};
if ($env->{PATH_INFO} =~ /\.js$/) {
$env->{PATH_INFO} =~ s/^\///;
my $js = $self->sprockets->concatenation($env->{PATH_INFO});
if ($js) {
return [ 200,
['Content-Type', 'application/javascript', 'Content-Length', length $js],
[$js]];
}
}
$env->{PATH_INFO} = $orig_path;
return $self->app->($env);
}
1;
__END__
=head1 NAME
Plack::Middleware::Sprockets - automatic javascript concatenation for Plack
=head1 SYNOPSIS
use Plack::Builder;
my $app = sub { ... } # as usual
builder {
enable "Plack::Middleware::Sprockets",
root => "/var/www/site_root", # local site root
load_paths => ["src/js", "src/extra/js"]; # directories for sprockets to search
$app;
};
=head1 DESCRIPTION
Plack::Middleware::Sprockets lets you use sprockets to include external
dependencies in your javascript files. These dependencies will automatically
be concatenated into a single file when the file is requested and found by
sprockets. If sprockets can not find the requested file in one of the
load_paths, it will pass on the request to the rest of the application.
=head1 SEE ALSO
L<Plack> L<Plack::Builder> L<Plack::Middleware::Text::SASS>
=cut
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment