relative_url_root in javascript

I just realized something that could make life much, much easier.

In my rails apps that utilize jQuery (pretty much all of them that have any complex interaction), I’m used to adding a line as follows to allow jQuery to include authenticity tokens in any ajax request:

<%= javascript_tag "var AUTH_TOKEN = #{form_authenticity_token.inspect};" if protect_against_forgery? %>

And yet, when I write ajax requests with any sort of time crunch, in the interest of speed I throw in absolute URL strings. What happens when I want to change the root URL for a project when deploying to Passenger, though?

I just realized that I can use the AUTH_TOKEN technique to give JS access to my root url string.

<%= javascript_tag "var RAILS_ROOT = '#{ActionController::Base.relative_url_root}';" %>

This gives me a variable RAILS_ROOT that I can prepend to any of my urls. It’s not the complete joy of resourceful named routing, but it’s one step closer to it without the overhead of parsing all of my js files through a controller.

Comments are closed.