You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/howto/serialize_poro.md
+51-4Lines changed: 51 additions & 4 deletions
Original file line number
Diff line number
Diff line change
@@ -2,13 +2,16 @@
2
2
3
3
# How to serialize a Plain-Old Ruby Object (PORO)
4
4
5
-
When you are first getting started with ActiveModelSerializers, it may seem only `ActiveRecord::Base` objects can be serializable, but pretty much any object can be serializable with ActiveModelSerializers. Here is an example of a PORO that is serializable:
5
+
### Using Duck Typing
6
+
When you are first getting started with ActiveModelSerializers, it may seem only `ActiveRecord::Base` objects can be serializable, but pretty much any object can be serializable with ActiveModelSerializers.
7
+
Here is an example of a PORO that is serializable just by implementing the needed methods:
8
+
6
9
```ruby
7
10
# my_model.rb
8
11
classMyModel
9
12
alias:read_attribute_for_serialization:send
10
13
attr_accessor:id, :name, :level
11
-
14
+
12
15
definitialize(attributes)
13
16
@id= attributes[:id]
14
17
@name= attributes[:name]
@@ -21,12 +24,56 @@ class MyModel
21
24
end
22
25
```
23
26
24
-
Fortunately, ActiveModelSerializers provides a [`ActiveModelSerializers::Model`](https://github.com/rails-api/active_model_serializers/blob/master/lib/active_model_serializers/model.rb) which you can use in production code that will make your PORO a lot cleaner. The above code now becomes:
27
+
### Inheriting ActiveModelSerializers::Model
28
+
Fortunately, ActiveModelSerializers provides a [`ActiveModelSerializers::Model`](https://github.com/rails-api/active_model_serializers/blob/master/lib/active_model_serializers/model.rb) which you can use in production code that will make your PORO a lot cleaner.
29
+
The above code now becomes:
25
30
```ruby
26
31
# my_model.rb
27
32
classMyModel < ActiveModelSerializers::Model
28
33
attr_accessor:id, :name, :level
29
34
end
30
35
```
31
36
32
-
The default serializer would be `MyModelSerializer`.
37
+
The default serializer would be `MyModelSerializer`.
38
+
39
+
### Serializing an instance
40
+
Sometimes you don't want to create yet another class just to serialize an object.
41
+
Well, athough it is recommended to have defined classes for what you serialize,
42
+
this is possible as well:
43
+
44
+
Given the following serializer:
45
+
46
+
```ruby
47
+
classApi::V1::UserSerializer
48
+
type :user#this is necessery, otherwise AMS will show your instance class name
49
+
50
+
attributes :id, :name
51
+
```
52
+
53
+
```ruby
54
+
classApi::V1::UsersController
55
+
defshow
56
+
#this is just an example
57
+
an_instance =OpenStruct.new(id:1, name:'Just an example')
0 commit comments