Ruby on Rails

Google AJAX Libraries on Rails

If you're reading this blog you've probably already heard about Google's AJAX Library API on many other news sites like Slashdot.

I'm going to describe my simple process for setting up a RoR app to use Google to pull the APIs in a rails friendly way, throughout layouts, views, and helpers.

First, open up "app/helpers/application_helper.rb". Here, we are going to add a few tag methods to keep our views clean and also to keep our versions consistent.

def google_loader_tag

  "<script type=\"text/javascript\" src=\"http://www.google.com/jsapi\"></script>"

end
 
def google_prototype_tag

  google_tag('prototype', '1.6.0.2')

end
def google_scriptaculous_tag

  google_tag('scriptaculous', '1.8.1')

end

# etc for any of the other libraries

private

def google_tag(name, version)

  "<script type=\"text/javascript\">google.load(\"#{name}\", \"#{version}\");</script>"

end

Now we need to include these tags in our layouts and views.

In my layout, I put this for a head:

<head>
<title><%= yield :title %> - My Site</title>
<%= stylesheet_link_tag 'mystyle' %>
<%= google_loader_tag %>
<%= yield :css_include %>
<%= yield :javascript_include %>
</head>

This lets me specify the page title, CSS, and Javascript, in the view, so we don't load in anything unnecessary.

Now here is what my view looks like:

<% content_for :title do -%>Welcome<% end -%>
<% content_for :javascript_include do -%><%= google_prototype_tag %><% end -%>

Now my title bubbles up, and my request for prototype bubbles up to the head for me, after the google loader.

The best part about this setup is that my versions will stay the same, and they only need to be changed in one place. And, if I ever decide to host the files locally, I just change the tags in one place, and make the google loader tag return "", until I fix all of the instances.

You've successfully subscribed to SmartLogic Blog
Great! Next, complete checkout for full access to SmartLogic Blog
Welcome back! You've successfully signed in.
Unable to sign you in. Please try again.
Success! Your account is fully activated, you now have access to all content.
Error! Stripe checkout failed.
Success! Your billing info is updated.
Error! Billing info update failed.