Cristian Cristian - 3 years ago 292
CoffeeScript Question

Use Rails Sprockets directives when rendering js from controller

I want, from a controller, to render a
view that includes another js file from the

#= require doc_ready

Why a view rendered by a controller instead of a static asset?

Because I want to refer to the file through an absolute url, that doesn't changes. Rails 4.0 only compiles assets with a digest like
and I want to use the same url (and possibly expire the cache file based on time), even if I make changes to the script.

Why an absolute url?

Because I want to use the script externally on another website, and the code I give to the webmaster of that site mustn't change.

Why do I want to include another js from the assets?

  1. To keep the code DRY

  2. To require a simple library that simulates the jquery ready event, used to create widgets on the page that included the script.

Can I achieve that by making a controller action that renders a
view, which compiles and includes other needed js files from the library, just like sprocket does when compiling assets?

Answer Source

Use redirection like so:

  def show
    redirect_to view_context.javascript_path('')

There is a way to render whole js file:

def show
  render text: Rails.application.assets.find_asset('').body
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download