Saturday, 24 March 2012

Ruby on Rails : How to include a page specific JavaScript file in Rails 3.1?

Rails 3.1 application has a new effective way to include a JavaScript file for a particular page without compromising the loading time by using Asset pipeline.

You all know that  in previous versions of Rails, all assets were located in subdirectories of public such as images,javascripts and stylesheets. With the asset pipeline, the preferred location for these assets is now the app/assets directory.Assets can still be placed in the public hierarchy. Any assets under public will be served as static files by the application or web server.

In production, Rails precompiles these files to public/assets by default. The precompiled copies are then served as static assets by the web server. The files in app/assets are never served directly in production.

If you want to add a JavaScript file for a particular page in your Rails 3.1 application,just follow the steps below ,its working fine for me.

  • Mention the JavaScript file name that you want to access from a particular page in Config -> environments -> production.rb like shown below.

Demo::Application.configure do

   config.assets.precompile += %w( application.css application.js flexpaper.js data_table.js public.js jquery.Jcrop.js jquery.Jcrop.min.js google_org_chart_query_wrapper.js jquery.jstree.js)

  • Mention the JavaScript file name that you want to include in a particular view page by using the JavaScript include tag like.

<%= javascript_include_tag "jquery.jstree" %>

  • After that you need to precompile the assets.You all know that Rails comes bundled with a rake task to compile the asset manifests and other files in the pipeline to the disk.Compiled assets are written to the location specified in config.assets.prefix. By default, this is the public/assets directory.

          The rake task is:

bundle exec rake assets:precompile 

1 comment:

  1. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging…!!..Ruby on Rails Online Training Hyderabad