Dangling RPC Fruit Off Of Your Rails' Controllers

Tuesday, November 05, 2013
by Ara T. Howard

when working on any non-hello-world rails application you invariably need teeny ajax helpers to communicate with the server - in order to perform client side logic. i'm not talking an api per-se, but ad-hoc utilities like this:

reservation.change(function(){check_availibity_on_the_server(reservation.val(),function(data){if(!data['available']){alert('that time is not available - pick another!');};})});

etc.

these types of functions aren't part of a server-to-server public api, they are just cooperating js/backend endpoints that are needed to make the view function.

most rails' applications will accumulate many of these and the question arises:

"Where do you put them?"

in most teams you'll have three or four developers naming and organizing these functions differently, ensuring that the code base turns into a cowboy spaghetti mess in short order.

@dojo4 we've abstracted this with a teeny rpc design pattern: first we have a teeny controller dsl that's included into our ApplicationController that allows declarative definitions of 'rpc' js helpers on a per-controller basis.

in plain english this dsl just defined a single action on the controller that multi-plexes which method to employ based on params, and an easy way to define them. it expects that all rpc actions will return a hash and give back json.

so, there you have it - a simple way to keep your rpc helper js from polluting your controllers and views with varied strategies and another example about how having brutally consistent interfaces makes abstraction possible and simple.