= Ajax
A Ruby on Rails plugin to augment a traditional Rails application with a completely AJAX frontend, while transparently handling issues important to both the enterprise and end users, such as testing, SEO and browser history.
The Ajax philosophy is that you should not have to develop for AJAX: Your code shouldn't change; your tests shouldn't change; and the way Google sees your site shouldn't change. (Coming soon, this link {AJAX site crawling specification}[http://code.google.com/web/ajaxcrawling/docs/getting-started.html] may obviate that.)
The beauty of Ajax is that your Rails application only ever sees traditional requests, so it does not have to be "Ajax aware".
Ajax is being used live in production on altnet.com[http://altnet.com], if you would like to try it out (as of May 1st 2010 or thereabouts).
== Install
After installing, create layouts in app/views/layouts/ajax/ that mimic your existing layouts. See Request Handling -> Layouts.
=== Rails 3
1. Add the gem to your Gemspec
gem 'ajax'
2. bundle install
3. rake ajax:install
=== Rails 2.x.x
As a Gem
1. Add the gem as a dependency in your config/environment.rb
config.gem 'ajax'
2. rake gems:install
3. Add to your Rakefile
begin
require 'ajax/tasks'
rescue Exception => e
puts "Warning, couldn't load gem tasks: #{e.message}! Skipping..."
end
4. rake ajax:install to install required files. This command is safe to run multiple times. It will skip existing files.
As a Plugin
./script/plugin install http://github.com/kjvarga/ajax.git
=== Sample Output
$ rake ajax:install
created: app/controllers/ajax_controller.rb
created: app/views/ajax/framework.html.erb
created: config/initializers/ajax.rb
created: public/javascripts/ajax.js
created: public/javascripts/jquery.address-1.2rc.js
created: public/javascripts/jquery.address-1.2rc.min.js
created: public/javascripts/jquery.json-2.2.min.js
created: public/images/loading-icon-small.gif
$ rake ajax:install
skipped: app/controllers/ajax_controller.rb exists!
skipped: app/views/ajax/framework.html.erb exists!
...
== Introduction
Ajax handles these common problems:
* SEO/Crawlability/Google Analytics support
* Browser History
* Bookmarkability / Deep-linking
* Redirects
* Cookies
* Lazy-loaded Assets
* Activating Tabs
* Request Rewriting & Redirecting
Ajax converts a traditional Rails application to use a completely AJAX frontend.
What do I mean by "completely AJAX"? Everyone uses AJAX. What we mean when we say "completely AJAX" is that the main page is only loaded once. Every link now loads content via AJAX.
But if we do that, the URL will never change and we will have no history, because that is how browsers determine history. It turns out the only way to change the URL without causing the browser to issue a new request, is to modify the named anchor - or "hashed" - part of the URL.
So now your traditional links auto-magically load content via AJAX into a page container and update the browser URL with the new URL. You have all the benefits of AJAX as well as history and link bookmarkability.
Where before you would have seen something like http://example.com/the-beatles/history, now you would see http://example.com/#/the-beatles/history. Notice the #/?
=== How does it work?
Ajax comprises Rack middleware, Rails integrations and some JavaScript libraries to handle everything from redirecting and rewriting incoming requests, to managing the response headers and content, to handling the browser URL, JavaScript callbacks and client-side events.
Browsers do not send the hashed part of the the URL with page requests, so to an AJAX-ed application, all requests look like they are for root.
In order to load the correct page we must first render a framework page with accompanying JavaScript. The JS examines the URL and then issues another request to the server for the hashed part (which may still be / if the user requested the home page).
=== An Example User Interaction
1. User pastes http://example.com/#/beyonce/albums into a browser.
2. Server receives request for http://example.com/ and renders the framework page.
4. AJAX request for http://example.com/beyonce/albums is initiated by client-side JavaScript, and received by the server.
5. Server renders http://example.com/beyonce/albums.
6. Response headers are processed and the response inserted into the page container.
=== Request Handling
Ajax uses a custom HTTP header Ajax-Info to pass JSON back and forth between the client and server. The client sends information about the state of the container, and the server sends new information back.
By default the current layout is sent in the Ajax-Info header. This can be useful for determining which assets to include, or layout to render in your response.
Ajax-Info headers with special meaning:
[title] Sets the page title.
[tab] jQuery selector, triggers the activate event on matched element(s).
[container] jQuery selector, the container to receive the content (default: default_container).
[assets] Hash of JavaScript and CSS assets to load { :javascripts => [], :stylesheets => [] }
[callbacks] List of string callbacks to execute after assets have finished loading.
=== Robots and External APIS
We detect robots by their User-Agent strings. If a robot is detected the Ajax handling is bypassed and the robot sees the traditional Rails application.
By default any AJAX or non-GET requests pass through unmodified.
If you need to expose external APIs you can do so using a regular expression that is matched against incoming URLs.
== Compatibility
You must be running jQuery 1.4.2 to use this plugin. Sorry, Prototype users.
The following JavaScript libraries are required and included in the plugin:
* {jQuery Address 1.2RC}[http://www.asual.com/jquery/address/]
* jQuery JSON 2.2
=== Ruby and Rails:
* Rails 2.3.4 running Ruby 1.8.7 and Ruby 1.9
* Rails 2.3.5 running Ruby 1.8.7 and Ruby 1.9
=== Browsers:
(See {jQuery address supported browsers}[http://www.asual.com/jquery/address/docs/].)
* Internet Explorer 6.0+
* Mozilla Firefox 1.0+
* Safari 1.3+
* Opera 9.5+
* Chrome 1.0+
* Camino 1.0+
= Documentation
Please browse the {API documentation at rDoc.info}[http://rdoc.info/projects/kjvarga/ajax]
== Configuration
It is important to be able to disable the plugin when you don't want it interfering, like when you are testing. You will also want to ensure that your site's JavaScript still works when the plugin is disabled.
To disable the plugin in your environment file:
# config/environments/test.rb
Ajax.enabled = false
If you need to, you can check the state of the plugin with:
Ajax.is_enabled?
Other onfiguration goes in config/initializers/ajax.rb such as indicating which links to except from the request processing. See Excepted Links.
== Ajax Layouts
Typically AJAX content does not render a layout because we just want to update a fragment of a page. Automatically turning off layouts when rendering AJAX is one option, but what about when we do want to use a layout?
My solution is to first look in app/views/layouts/ajax/ for a layout with the same name as the default layout for the current action. If a layout is found, we use it, otherwise the default layout is used.
In your Ajax layouts you can define callbacks, tabs to activate or the container to receive content.
For example, our layouts:
layouts/
_assets.html.haml
ajax/
application.html.haml
single_column.html.haml
two_column.html.haml
application.html.haml
single_column.html.haml
two_column.html.haml
Gists
* {ajax/application.html.haml}[http://gist.github.com/373133#file_application.html.haml]
* {ajax/two_column.html.haml}[http://gist.github.com/373133#file_two_column.html.haml]
== Link Handling
All links which are rendered using the link_to (or any other url) helper method automatically include a data-deep-link attribute containing the path from the link's HREF.
The Ajax JavaScript class listens for clicks on any link with a data-deep-link attribute and loads the link's content using AJAX.
Should you need to, you can set this attribute on a link by passing in HTML options to link_to:
link_to odd_url, {}, { :data-deep-link => '/even/odder/url' }
To manually mark a link as traditional, pass :traditional => true or :data-deep-link => nil.
=== Excepted Links
Excepted links bypass Ajax request and link handling. I call these traditional links.
Links can be excepted by passing in strings or regular expressions to Ajax.exclude_paths(). Only pass the path and not the full URL. The path will be modified to match against other paths as well as against full URLs:
# config/initializers/ajax.rb
Ajax.exclude_paths %w[ /login /logout /signup /altnet-pro /my-account/edit /user-session/new ]
Ajax.exclude_paths [%r[\/my-account\/.*]]
Typically, we except pages that require HTTPS, like signup forms, because including secure forms on an insecure page often triggers a browser warning.
Excepted links when rendered do not contain the data-deep-link attribute if they are rendered with the link_to (or any other url) helper method.
== Rails Helpers
Use the ajax_header helper in your controllers or views to add data to the Ajax-Info header. Values are converted to JSON before being sent over the wire. Internally this function uses Ajax.set_header.
You can use Ajax.get_header to inspect Ajax-Info header values. See the In Views example.
=== In Controllers
In controllers, ajax_header uses an after_filter to add content to the response. It therefore accepts passing a block instead of a static value, as well as :only and :except modifiers, e.g:
# app/controllers/application_controller.rb
ajax_header :title { dynamic_page_attribute(:page_title) || "Music @ Altnet" }
ajax_header :assets do
{ :stylesheets => [current_controller_stylesheet] }
end
# app/controllers/browse_controller.rb
ajax_header :tab, '#header .nav li:contains(Music)', :only => [:music, :artists, :albums, :tracks, :new_releases]
ajax_header :tab, '#header .nav li:contains(Playlists)', :only => :playlists
ajax_header :tab, '#header .nav li:contains(DJs)', :only => :djs
# app/controllers/activity_controller.rb
ajax_header :tab, '#header .nav li:contains(Realtime)'
ajax_header :assets, { :javascripts => javascript_files_for_expansion(:juggernaut_jquery) }
Array and Hash values are merged so you can call ajax_header multiple times. For example, the asset Hash and Array values will be merged.
=== In Views
The syntax is similar to the controller version, except that we do not use an after_filter, so you cannot pass a block or :only and :except modifiers.
See {ajax/two_column.html.haml}[http://gist.github.com/373133#file_two_column.html.haml] for an example.
== Lazy-loading Assets
Use ajax_header :assets { :stylesheets => [], :javascripts => [] }
to define assets that a page depends on. These assets will be loaded before the response content is inserted into the DOM.
Assets that have already been loaded are not loaded again, so it is safe to always include the assets header.
If you need to perform operations on the new content, or instantiate objects defined in the dependent assets, use JavaScript Callbacks.
== JavaScript Callbacks
To add a JavaScript callback(s) that will be executed after any assets in Ajax-Info['assets'] have been loaded you can pass it in the header with the following. These callbacks are executed in the global scope:
ajax_header, :callbacks, 'window.player.init();'
Alternatively you may want to bind callbacks directly to the window.ajax object in your view:
# app/views/activity/recent.html.haml
window.ajax.onLoad('window.juggernaut = new Juggernaut(#{juggernaut_options.to_json}); window.liveFeed.init();');
window.ajax.prependOnLoad("$(document).trigger('player.init');");
When we add the juggernaut callback it must be a string because Juggernaut is defined in one of the assets that hasn't been loaded yet.
window.ajax.prependOnLoad adds the callback to the front of the queue. Callbacks can also be functions, for example:
window.ajax.onLoad(function() {
alert('All your asset are ours!');
});
== Contributions
Contributions are welcome. Please fork the project and send me a pull request with your changes and Spec tests.
== Useful Resources
* AjaxPatters[http://ajaxpatterns.org/Unique_URLs] useful discussion of techniques for maintaining state using JavaScript to poll for changes to window.location.hash.
* link jQuery Address[http://www.asual.com/jquery/address/] JavaScript library for managing the URL.
* SWFAddress[http://www.asual.com/swfaddress/] deep linking solution for Flash.
Copyright (c) 2010 Karl Varga, released under the MIT license