Grime

Provides a basic JSON CRUD API controller base class.

Installation

Add this line to your application's Gemfile:

gem 'grime'

And then execute:

$ bundle

Or install it yourself as:

$ gem install grime

Usage

Basic API controller

Subclass Grime::ApiController for each model you'd like an API for:

class PeopleController < Grime::ApiController

  def object_params
    params.require(:person).permit(:name, :age)
  end

  def filter_params
    params[:filter].permit(:name, :age)
  end

end

NOTE: overriding object_params is not strictly required, but without it the controller will allow mass-assignment of ALL attributes of the underlying model. A warning will be printed to the log to remind you that this is bad.

Similarly, overriding filter_params is not required - but by default ANYTHING passed in params[:filter] will be passed to where, including arrays and nested hashes. A warning will be printed in this case as well.

Customization

The operation of Grime::ApiController can be customized further by overriding methods.

  • object_class: by default, the model class is determined from the controller name. Override this method to specify a different class.

  • scope: by default, this is simply object_class. Override it to supply a Relation to use when creating / finding objects.

  • object_params_for_create / object_params_for_update: by default, object_params are used for both creation and updates. If different parameters are allowed for different actions, override these methods to specify them.

Error Conditions

There are several possible error conditions:

  • record not found: results in an HTTP 404 status code and a payload of { "error": "not_found" }

  • missing required parameters: results in an HTTP 400 status code and a payload of { "error": "missing_parameters", "message": "param not found: person" }

  • parameters that are not allowed: results in an HTTP 400 status code and a payload of { "error": "unpermitted_parameters", "message": "found unpermitted parameters: updated_at" }

  • record fails validation: results in an HTTP 422 status code and a payload of: { "errors": { "name" => ["cannot be blank"] } } where each value under errors is an attribute and its corresponding error messages.

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request