Help developers expose APIs for their applications similar to Google AJAX Search.
The only dependency is the Rails 1.2+ (for the to_json method).
script/plugin install http://svn.simpltry.com/plugins/js_on_demand
script/generate controller js api
app/views/js/api.rhtml
<%= required_js_on_demand %>
var GetListing = function(id, callback) {
<%= js_on_demand_get(:action => "listing",
:js_parameters => {:serverId => "id"}) %>
}
app/controllers/js_controller.rb
I have mocked up a few fake results, obviously, you could read from a db or another web-service if you so chose. Here I have added the listing method referred to in the API.
def listing
mocked_data = {
"1" => "Listing 1",
"2" => "Listing 2",
"3" => "Listing 3",
"4" => "Listing 4",
"5" => "Listing 5",
"6" => "Listing 6"
}
data = {:listing => "Not Found"}
id = params[:serverId]
if mocked_data.has_key?(id)
data[:listing] = mocked_data[id]
end
render_js_on_demand(data)
end
<html>
<head>
<script src="http://localhost:3000/js/api"
type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">
//very bad, use unobtrusive!
function showListing(id) {
GetListing(id, function(data) {
alert(data.listing);
return false;
});
}
</script>
</head>
<body id="test_api">
<a href="#" onclick="return showListing(1)">listing 1</a>
<br />
<a href="#" onclick="return showListing(4)">listing 4</a>
<br />
<a href="#" onclick="return showListing(6)">listing 6</a>
<br />
<a href="#" onclick="return showListing(60)">listing 60</a>
</body>
</html>
That’s It! You have a fully working, albeit worthless, API. I showed you every file I changed in a fresh rails app.
A few things to note. Any parameters passed into js_on_demand_get (besides :js_parameters and :callback) get forwarded to url_for to construct the base url. The point is, your two methods don’t need to be in the same controller. Also, there is fairly decent tests written. Feel free to look in the test directory and tell me if you think this isn’t tested well enough. One last thing I should note, I have never written any ruby plugins before, and if something doesn’t feel right please drop me a line.
And here are the files that I modified to demo this plugin.
More information can be found in the README file. There may be some redundancy there, but it is much more technical.