How to add specific elements of the object pipeline?

I am writing a Rails 3.2.1 application and I have javascript code that I would like to include in one action. It just calls the jquery plugin and starts the countdown, but I would like to write it in a coffee script, and I feel that the resource pipeline is the right tool for this.

I also need access to the variables passed by the controller, for example @question . How should I do it? I studied the coffeebeans stone, but it only works for forms and links :remote=>true .

+4
source share
1 answer

Your problem can be solved in different ways.

Dynamically add assets

  • Add the following method to our application helper:

     module ApplicationHelper def include_related_asset(asset) # v-----{Change this} if !YourApp::Application.assets.find_asset(asset).nil? case asset.split('.')[-1] when 'js' javascript_include_tag asset when 'css' stylesheet_link_tag asset end end end end 
  • Call the helper method in layout -file:

     <%= include_related_asset(params[:controller].to_param + '_' + params[:action].to_param . 'js') %> 
  • Create specific assets for the actions of your controller. E. g. controller_action.js

Use yield

  • Add <%= yield :head%> to your layout.
  • Include your assets from your actions:

     <% content_for :head do %> <%= javascript_include_tag 'controller_action' %> <% end %> 

See the Rails guide for more information.


To pass controller data to your javascript, you can do:

  <%= javascript_tag do %> window.error_message = '<%= j error_message %>'; <% end %> 

See RailCast Episode # 324 for more information.

+1
source

Source: https://habr.com/ru/post/1395023/


All Articles