Rails' Asset Pipeline and JQPlot

We recently upgraded one of our internal Rails projects to 3.1 and included the asset pipeline as part of the upgrade. Everything worked peachy in development, but when we'd compile and compress our JS assets, our JQPlot charting library would not work. It kept throwing errors like:

  TypeError: Result of expression '$.jqplot' [undefined] is not a function
  TypeError: Result of expression 'getRootNode()' [undefined] is not an object

After digging around, it turns out that the problem was with how JQPlot was loading itself.

JQplot recommends that you include the file, jquery.jqplot.js, and then any additional modules you need. It turns out that this initial file actually appends your DOM with about 15 other JQPlot javascript files that constitue the core of the framework. Since the asset pipeline was not compressing all of JQPlot's core files, the loader library was essentially non-functional. Hence the type errors of undefined objects named $.jqPlot.

The solution was to ditch the included loader JS file, and create an equivalent file that works with Rails' asset pipeline. This involved making a file, app/assets/jqplot.js:

All the files in this loader file are from the jquery.jqplot.js file itself.

Our app/assets/application.js file then looks like this:

Once we had properly defined the files needed for our charting library, the compressed assets worked perfectly.

The lesson here is that there will be Javascript libraries out there that try to be helpful and create unusual functionality to load themselves into your browser. You must be aware of this when using the asset pipeline to catch these edge cases and be able to properly handle them.

Tags: tech