Putting ExtJS 4 into Rails 3.1's asset pipeline

Suraj N. Kurapati


ExtJS 4’s MVC architecture organizes source files in the following structure so that its Ext.Loader class can dynamically fetch and load the necessary Javascript files at runtime.

In a Rails 3.1 application, you can place the above structure under the app/assets/javascripts directory and package it as a monolithic Javascript asset using Rails 3.1’s asset pipeline by adding the following snippet to the app/assets/javascripts/application.js file:

//= require_tree ./app/model
//= require_tree ./app/store
//= require_tree ./app/view
//= require_tree ./app/controller
//= require app

Next, add an .erb extension to the app/assets/javascripts/app.js file and then register the packaged ExtJS 4 MVC components by adding the following snippet to the app/assets/javascripts/app.js.erb file:

Ext.application({
<% Dir[File.expand_path('../app/*/', __FILE__)].each do |subdir| %>
  <%= File.basename(subdir) %>s: <%=
    # omit all file extensions (js, js.erb, etc.) from the file name
    Dir[subdir + '/*.js*'].map {|f| File.basename(f)[/^[^.]+/] }.to_json
  %>,
<% end %>
// ... the rest of your ExtJS 4 application definition goes here ...
});

You now have ExtJS 4’s MVC architecture in Rails 3.1’s asset pipeline. :-)

Note that, during development, the asset pipeline caches the result of rendering the app/assets/javascripts/app.js.erb file in memory. As a result, if you add new files to or remove existing files from the app/assets/javascripts/app/ directory tree, then you must either (1) modify the public/javascripts/app.js file and reload your browser or (2) restart your Rails application (web server) to force the asset pipeline to render and cache the new output.


Updates