title: Client-side dynamic asset URLs in the Rails 3.1 asset pipeline
body: <h1>TL;DR</h1>
  
  <p>I'm trying to dynamically generate an asset URL using HTML5 data elements, on the client-side. This means the asset name isn't available until runtime in the browser, which prevents ERB from pre-processing on the server.</p>
  
  <p>Is there a work-around or best practice for handling such a situation?</p>
  
  <h1>Background</h1>
  
  <p>I'm using the <a href="http://www.fusioncharts.com/" rel="nofollow">Fusion Charts</a> charting plugin in a Rails application, which uses various SWF files to generate charts. I'm in the process of upgrading the application to Rails 3.1 and have placed these SWF files into <code>/vendor/assets/javascripts/fusion_charts</code>. </p>
  
  <p>Within the application, I dynamically specify the type of chart to draw using HTML5 data attributes, like so: </p>
  
  <pre class="lang-html prettyprint-override"><code>&lt;%# ... metric.html.erb ... %&gt;
  &lt;div id='chart-container' class='fusion-chart'
    data-chart-type='MSLine'
    data-source-url="&lt;%= @metric.data_url %&gt;"&gt;
  </code></pre>
  
  <p>Then I have a simple jQuery plugin written in CoffeeScript that pulls these data attributes and wires things to Fusion Charts:</p>
  
  <pre class="lang-js prettyprint-override"><code>// ... charting_plugin.js.coffee ...
  chart = new FusionCharts
    swfUrl: "/assets/fusion_charts/#{data.chartType}.swf"
  chart.setJSONUrl data.sourceUrl
  chart.render containerId
  </code></pre>
  
  <p>The problem I'm running into is the <code>swfUrl</code> argument. To follow the guidance offered in the <a href="http://guides.rubyonrails.org/asset_pipeline.html" rel="nofollow">RoR Asset Pipeline guide</a>, I should use the <code>asset_path</code> helper in ERB, but this won't work because <code>data.chartType</code> is bound on the client, at run-time, and can't be pre-processed server-side.</p>
  
  <pre><code>&lt;# ... charting_plugin.js.coffee.erb: This won't work; data.chartType isn't defined ... %&gt;
  chart = new FusionCharts
    swfUrl: "&lt;%= asset_path "fusion_charts/#{data.chartType}.swf" %&gt;"
  chart.setJSONUrl data.sourceUrl
  chart.render containerId
  </code></pre>
  
  <h1>Work Arounds</h1>
  
  <p>The simplest work-around (the one I'm using currently) is to simply move the SWF files back into <code>/public/fusion_charts</code> and not worry about the asset fingerprinting complexity of the pipeline. That said, I'm new to the pipeline, so maybe I'm missing something obvious.</p>
  
  <p>Is there a better way to handle client-side asset URLs like this?</p>