Sunday, October 7, 2012

Changing Dancer::Plugin::Ajax's content type

Dancer does lots of great things. It has a nice clean way to define routes to handle AJAX routes using the plugin Dancer::Plugin::Ajax.

ajax routes are defined in a clear way:

ajax '/stuff' => sub {
  # do work and return
};

This plugin technique allows for clear way to separate between ajax and other types of actions for the same route.

ajax '/stuff' => sub {
   # do ajax-y stuff here
};

get '/stuff' => sub {
   # handle html response
};

Unfortunately, the one negative with Dancer::Plugin::Ajax is that is assumes all responses will be XML.

A quick fix is to manually set the content type in each ajax handler.

ajax '/stuff' => sub {
   content_type('application/json');
   
   # do work
};
or add set it as a general option in your main before hook or in each prefix route handler like:
package WebApp;

hook before => sub {
   if ( request->is_ajax ) {
      content_type('application/json');
   }
};

Both of these solutions feel kind of clunky due to the level of duplication. Our app returns JSON or HTML snippets and never uses XML. This redundancy in code led me to creating a patch for Dancer that allows default Ajax content_type to be set in the config file. (see issue 840).

Config Example:

  plugins:
    ajax:
      content_type: 'application/json'

__END__

No comments:

Post a Comment