A lot of people ask me whether we use Rails controllers for our API. We don’t, we use Grape. Grape is a Rack-based system and a DSL that provides a cleaner separation, some API-specific functionality and generally a better syntax. Now that we have dealt with exceptions and authentication we realized that the amount of functionality exposed in the API has grown exponentially in one single Ruby file. Let’s refactor it into modules.
Here’s our current code from API v1.
We want a separate file for helpers and for the me API. We can move the helpers into a module and include it normally.
The namespace DSL is a bit tricky. Those namespace and get are actually namespace functions in Grape::API. Fortunately Ruby calls included(module) for every included module. We can call the public methods on a namespace function ourselves.
Let’s combine all of this into an API class.
The nice thing about this implementation is that we can now compose an API v2 with a bunch of v1 modules and some v2 ones. The not-so-nice part is the included construct. I’d like to write the following.
Beer to anyone who can implement this, I tried for hours, in vain - I think Grape will need some major refactoring to support modules this way. Fork Grape on Github.