Few days ago a new project was thrown in my face ;). And it was interesting I must say – extracting some heavy internals of existing application into internal API + external client (app), that could be developed further with some additional features.
ActiveResource was extracted into separate gem in Rails 4, and it basically allows you to route actions on you model to REST API. So you get almost all the benefits as using regular ActiveRecord model like associations, query methods etc. Sounds cool, right? So how to do it in few general steps:
first you need to build your API, you may have some kind of existing API already in your app, you may even want to build even external API that will serve data on behalf of you app, there are so many different cases you wouldn’t guess :). You can go with rails, with rails-api or even something like [grape] (grape sound really cool if you want to build something light-weight from scratch).
Now that you have basic API setup it’s time to communicate with it. ActiveResource have very poor readme, but great RDoc (that’s a shame, to be honest I prefer just having rock-solid readme file, but maybe that’s just me :P). Few tips you might find useful:
How to modify ActiveResource headers?
Let’s say you want to authenticate by checking
HTTP_SECRET header, so let’s create a base class that all of your ActiveResource models will inherit from.
1 2 3
See why this works – source.
How to paginate with ActiveResource?
You can go with not so restful way by using
ActiveResource::Collection. See this gist I stolen this blogpost (check this out, it’s very useful <3). Or you can use activeresource-response that have full working example how to implement REST pagination with kaminari. It’s that simple. In case you are using will_paginate on your API side, this should help a little:
1 2 3 4 5 6 7 8 9
On the API side you might also use will_paginate, in that case you can just require
will_paginate/array (in initializer for example) and paginate array directly by calling
.paginate(options) with proper total/page/per_page values – see source.
How to handle remote validation?
You probably don’t want to duplicate validation logic in both API server and the client. So it makes sense to just return validation errors to ActiveResource in a way it can understand it. It should be enough to respond with status 422 (ActiveResource::ResourceInvalid) and pass validation errors:
Testing & mocks
ActiveResource provides HttpMock class, that allows you to register mock responses. Taken from docs:
1 2 3 4 5 6 7
You can clear defined request by calling
ActiveResource::HttpMock.reset!. If you want to raise an error, you can trigger it by setting proper response code. Once again, taken from docs:
1 2 3 4 5 6 7 8 9 10 11 12 13