A common pattern in a Rails controller action is to
- Fetch a resource
- Do something to the resource (optional)
- Return the resource in a serialized format.
I am looking for a library that abstracts away the first step, so that my controller actions can assume a resource was successfully fetched and avoid checks for exceptional cases.
For example, here is a hypothetical show
action:
def show
attrs = params.slice(:handle, :provider)
account = Account.find_by(attrs)
if account
respond_with account
else
head 404
end
end
And what I want is something more like this:
# controller
def show
respond_with resource
end
# some initializer (basically pseudocode)
resource do |params|
attrs = params.slice(:handle, :provider)
Account.find_by(attrs)
end
Where the library would handle returning a 404 if find_by
returns nil, or 400 if the provided params are invalid (missing :handle key, include an extra :id key, etc.).
Does anyone know of a library that provides something like this? It is a great use case for a Rack middleware on top of Application.routes
.