3

I have a Coffeescript view, something like widget.js.coffee which needs to include jQuery, as I can't be sure that jQuery is available. This idea is for other people to use the JS file, e.g.

<script src="http://my.rails.app/40/widget.js"></script>

My app already has jQuery via the asset pipeline, so I want to do the equivalent of the application.coffee manifest, where I can simply say something like:

#= require jquery

So far, it looks like I can output jQuery via so:

<%= Rails.application.assets["jquery"].source %>

but this seems to break the Coffeescript code (looks like there are backticks in the jQuery source).

I'm not sure the best way to proceed. Any thoughts on the best way to do this?

Scott Arbeitman
  • 311
  • 2
  • 15
  • Have you any more context? For example, if you're loading this without knowing JQuery has been loaded - I take it's after you load an ajax response or something? – Richard Peck Jul 07 '14 at 06:59
  • I've seen around in CoffeScript using `$ = require('jquery')`... Maybe you should work around this... – Ruby Racer Jul 07 '14 at 07:12

1 Answers1

0
  1. Make a .coffee file in the asset pipeline that includes all the libraries you require. Let's call it "widget.js.coffee" and it lives in assets/javascripts
  2. In your controller, pull the generated source like so:

    code = Rails.application.assets['widget'].source

  3. Compress it

    @js_libraries = Uglifier.compile code

  4. Use it in your view. If your view is coffeescrtipt, make sure it is enclosed in backticks

    <%= raw @js_libraries %>

Scott Arbeitman
  • 311
  • 2
  • 15