Search code examples
ruby-on-rails-3.1renderingcoffeescriptpartials

Cannot render coffeescript partial inside coffeescript


I want to make a general controller that can be called after the page was loaded (with AJAX) and update different stuff on the page depending on which controller called it.

The purpose is to allow better page and fragment caching, while displaying custom elements for the users.

My framework looks like this:

controllers/general_ajax_controller.rb
views/general_ajax/on_page_load.js.coffee
                 ./_update_some_stuff.js.coffee

The on_page_load action in the controller handles the logic of figuring out which partials to load and the view will render the partials.

In the on_page_load.js.coffee view I have this code (simplified):

<%= render "update_some_stuff" %>

which should render the partial. Instead I get this error:

  ActionView::Template::Error (SyntaxError: Reserved word "function" on line 2):
  app/views/general_ajax/on_page_load.js.coffee:1:in `_app_views_general_ajax_on_page_load_js_coffee___2304196970850216490_70321203283120'

I think that the coffeescript is compiled before including it in the view (which is coffee and does not support compiled js)

If I change the extension of the on_page_load view to .js.erb then it works. (Oddly enough, I have to restart my server before it works, do you know why?)

Do you think this is an issue in coffeescript or is it bad practice and therefore not supported?

As a side discussion, what do you think of my approach to dynamic scrips?


Solution

  • That's because _update_some_stuff.js.coffee is interpreted and converted to Javascript. When it is inserted into on_page_load.js.coffee it raises an error because vanilla Javascript code is not compatible inside a Coffee-Script file (the function keyword in this case).