Skip to content

Commit

Permalink
doc: add documentation about Alba
Browse files Browse the repository at this point in the history
  • Loading branch information
leoncruz committed Jun 25, 2023
1 parent a1e9192 commit 4174542
Showing 1 changed file with 34 additions and 6 deletions.
40 changes: 34 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ A gem to standardize json responses in Rails applications, highly inspired on [R
## Table of Contents
- [Usage](#usage)
- [Respondering json](#respondering-json)
- [Data Serialization](#data-serialization)
- [Success and failure actions](#success-and-failure-actions)
- [Errors](#errors)
- [Message](#message)
Expand Down Expand Up @@ -91,6 +92,22 @@ The response will be like:
}
```

### Data Serialization

This gem is integrated to [Alba](https://github.com/okuramasafumi/Alba) to create your `resources`. A simple resource example:
```ruby
class UserResource
include Alba::Resource

attributes :id, :name, :email
end
```
When the `render_json` methods receive an instance of `user` or a `ActiveRecord::Relation` of `users` will search by `UserResource`.

If you have a nested controller like: `Api::V1::UsersController`, `mini_api` will search by resources in controller namespace.
First will search per `Api::V1::UserResource`, after `Api::UserResource` and then `UserResource` until find.
That way, even if your `controller` and `resource` are defined in different namespace levels, `MiniApi` will find.

### Success and failure actions

Many times, our controller actions need to persist or validate some data coming from request, the default approach to do that is like:
Expand Down Expand Up @@ -144,19 +161,30 @@ The `message` key is different based on actions on informed model: create, updat
You can respond any type of data, but ActiveRecord/ActiveModel::Model and ActiveRecord::Relation has a special treatment as shown above

### Errors
To show errors of a model, by default will use the `errors.messages` method, but `MiniApi` adds an ability to `active_model_serializers` to create a error serializer
as a nested class in your serializer. Example:
To show errors of a model, by default will use the `errors.messages` method, but `MiniApi` adds an ability to `Alba` to create a error resource
as a nested class in your resource. Example:

```ruby
class UserResource
include Alba::Resource

attributes :id, :name, :email

class Error
include Alba::Resource

attribute :user do
object.errors.full_messages
end
end
end
```
The response will be like:
```json
{
"success": false,
"errors": {
"user": {
"first_name": "can't be blank",
"last_name": "can't be blank"
}
"user": ["First name can't be blank"]
},
"message": "User could not be created."
}
Expand Down

0 comments on commit 4174542

Please sign in to comment.