Skip to content

Commit

Permalink
Improve serializer_attributes section
Browse files Browse the repository at this point in the history
  • Loading branch information
ElMassimo committed Nov 7, 2020
1 parent e8f1647 commit 2d12dd0
Showing 1 changed file with 19 additions and 16 deletions.
35 changes: 19 additions & 16 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ Oj Serializers
JSON serializers for Ruby, built on top of the powerful [`oj`][oj] library.

[oj]: https://github.com/ohler55/oj
[mongoid]: https://github.com/mongodb/mongoid
[ams]: https://github.com/rails-api/active_model_serializers
[jsonapi]: https://github.com/jsonapi-serializer/jsonapi-serializer
[panko]: https://github.com/panko-serializer/panko_serializer
Expand Down Expand Up @@ -236,8 +237,6 @@ maintainable.

Obtains the attribute value by calling a method defined in the serializer.

The serializer's attribute methods can access the object being serialized as `object`,
or by the serializer name (without the `Serializer` suffix).

You may call [`serializer_attributes`](https://github.com/ElMassimo/oj_serializers/blob/master/spec/support/serializers/song_serializer.rb#L13-L15) or use the `attribute` inline syntax:

Expand All @@ -250,21 +249,10 @@ class PlayerSerializer < Oj::Serializer
end
```

### `mongo_attributes` 🚀

Reads data directly from the document `attributes`, with the addition that if
you specify `:id`, it will read serialize `_id` as `id`.
Instance methods can access the object by the serializer name without the
`Serializer` suffix, `player` in the example above, or directly as `@object`.

By skipping type casting, coercion, and defaults, it [achieves the best performance][raw_benchmarks].

Although there are some downsides, depending on how consistent your schema is,
and which kind of consumer the API has, it can be really powerful.

```ruby
class AlbumSerializer < Oj::Serializer
mongo_attributes :id, :name
end
```
You can customize this by using [`object_as`](https://github.com/ElMassimo/oj_serializers#using-a-different-alias-for-the-internal-object).

### `ams_attributes` 🐌

Expand Down Expand Up @@ -299,6 +287,21 @@ PersonSerializer.one('first_name' => 'Mary', :middle_name => 'Jane', :last_name
# {"first_name":"Mary","last_name":"Watson"}
```

### `mongo_attributes` 🚀

Reads data directly from `attributes` in a [Mongoid] document.

By skipping type casting, coercion, and defaults, it [achieves the best performance][raw_benchmarks].

Although there are some downsides, depending on how consistent your schema is,
and which kind of consumer the API has, it can be really powerful.

```ruby
class AlbumSerializer < Oj::Serializer
mongo_attributes :id, :name
end
```

## Associations DSL 🛠

Use `has_one` to serialize individual objects, and `has_many` to serialize a collection.
Expand Down

0 comments on commit 2d12dd0

Please sign in to comment.