Building an Adapter
If you find yourself repeatedly making customizations to a group of
Resource
s and seek DRYer code, package those customizations into an
Adapter
. Here we’ll be starting from a previous how-to, How to Use
Alternate ORMs.
You can follow along with the below code snippets, or view the diff on github.
Adapters are simpler than you might think. It’s little more than copy-pasting those low-level customizations into a common class.
Start by creating lib/elasticsearch_adapter.rb
. Cut/past the sorting,
pagination, and #resolve
overrides from EmployeeResource
into the adapter,
turning into def
methods along the way:
Ensure our adapter gets loaded:
And switch to that adapter in EmployeeResource
:
Bounce your server. You can still hit the /api/v1/employees
endpoint
with the same sort and paginate functionality, but the code has been
moved to an adapter.
Let’s ensure our users can filter as well:
For all the methods and functionality an adapter supports, see the Adapter documenation.
We probably also want has_many
-style macros to avoid writing similar
allow_sideload
code time after time. Start by specifying where this
functionality is defined, and add a has_many
macro:
The instance_eval
is there so we can always drop down to a lower-level
customization in our Resource
.
We can basically cut/paste our existing sideload code and rewrite it as variables:
You can now remove any customizations from your Resource
classes. You
can continue to build the adapter, adding belongs_to
, statistics, and
more. View the adapter documentation for the full API.