json-serializer 0.0.2 → 0.0.3

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA1:
3
- metadata.gz: 5c3b213846356d505bf946009f19f587a20e301e
4
- data.tar.gz: 12c14f7d92d96007edab556bf905b20bd9988c27
3
+ metadata.gz: 4d1ee255e70be3621c476154123e03ad6bec649d
4
+ data.tar.gz: ea26a50a35097eec83e8a3a505d7d447436d5a49
5
5
  SHA512:
6
- metadata.gz: 173509cdc07739213ad667d90bd1f8c3d121caf978e9e4ef05eaab0398d3eead13e832daa1f36293ec41f08ffd3199f92064280e5dfe29ae91b8b426c8bb140c
7
- data.tar.gz: 4551bfafedf3e5879efe06bbff3f1ddd091212fd54b616c1bf6aa05e97bb1d8cb26df2799c5b8981a346b73761a3d26c36b6930e8d85e387bee0635be9274643
6
+ metadata.gz: 73a0717218dad551abb4d73c4478ae27e2aa8c302d5a99d42867564452d96b69ddf86fec2d95be03964de9982bf15af931c4c4e23b11e8d32a6e3a7f9717a78b
7
+ data.tar.gz: 1acb1d09c30670ee406fbc19f3ed94d1f72a72259d43f9f9c9ccd8006134b30397b5db2473da59521241a6f6c33d5523a053a4fab2805f4304b30d1b7ad9e0fe
data/.gems ADDED
@@ -0,0 +1 @@
1
+ cutest -v 1.2.1
data/README.md CHANGED
@@ -1,6 +1,195 @@
1
1
  json-serializer
2
2
  ===============
3
3
 
4
- `ActiveModel::Serializers` outside Rails.
4
+ Customizes JSON output through serializer objects.
5
5
 
6
- Not ready.
6
+ A minimal implementation of [active_model_serializers][active_model_serializers] gem.
7
+
8
+ Installation
9
+ ------------
10
+
11
+ ```
12
+ gem install json-serializer
13
+ ```
14
+
15
+ Usage
16
+ -----
17
+
18
+ ### Basics
19
+
20
+ Here's a simple example:
21
+
22
+ ```ruby
23
+ require "json_serializer"
24
+
25
+ class UserSerializer < JsonSerializer
26
+ attribute :id
27
+ attribute :first_name
28
+ attribute :last_name
29
+ end
30
+ ```
31
+
32
+ In this case, we defined a new serializer class and specified the attributes
33
+ we would like to include in the serialized form.
34
+
35
+ ```ruby
36
+ user = User.create(first_name: "Sonny", last_name: "Moore", admin: true)
37
+
38
+ UserSerializer.new(user).to_json
39
+ # => "{\"id\":1,\"first_name\":\"Sonny\",\"last_name\":\"Moore\"}"
40
+ ```
41
+
42
+ You can add a root to the outputted json through the `:root` option:
43
+
44
+ ```ruby
45
+ user = User.create(first_name: "Sonny", last_name: "Moore", admin: true)
46
+
47
+ UserSerializer.new(user).to_json(root: :user)
48
+ # => "{\"user\":{\"id\":1,\"first_name\":\"Sonny\",\"last_name\":\"Moore\"}}"
49
+ ```
50
+
51
+ ### Arrays
52
+
53
+ A serializer can be used for objects contained in an array:
54
+
55
+ ```ruby
56
+ require "json_serializer"
57
+
58
+ class PostSerializer < JsonSerializer
59
+ attribute :id
60
+ attribute :title
61
+ attribute :body
62
+ end
63
+
64
+ posts = []
65
+ posts << Post.create(title: "Post 1", body: "Hello!")
66
+ posts << Post.create(title: "Post 2", body: "Goodbye!")
67
+
68
+ PostSerializer.new(posts).to_json
69
+ ```
70
+
71
+ Given the example above, it will return a json output like:
72
+
73
+ ```json
74
+ [
75
+ { "id": 1, "title": "Post 1", "body": "Hello!" },
76
+ { "id": 2, "title": "Post 2", "body": "Goodbye!" }
77
+ ]
78
+ ```
79
+
80
+ ### Attributes
81
+
82
+ By default, before looking up the attribute on the object, it checks the presence
83
+ of a method with the name of the attribute. This allow serializes to include
84
+ properties in addition to the object attributes or customize the result of a
85
+ specified attribute. You can access the object being serialized with the +object+
86
+ method.
87
+
88
+ ```ruby
89
+ require "json_serializer"
90
+
91
+ class UserSerializer < JsonSerializer
92
+ attribute :id
93
+ attribute :first_name
94
+ attribute :last_name
95
+ attribute :full_name
96
+
97
+ def full_name
98
+ object.first_name + " " + object.last_name
99
+ end
100
+ end
101
+
102
+ user = User.create(first_name: "Sonny", last_name: "Moore")
103
+
104
+ UserSerializer.new(user).to_json
105
+ # => "{\"id\":1,\"first_name\":\"Sonny\",\"last_name\":\"Moore\",\"full_name\":\"Sonny Moore\"}"
106
+ ```
107
+
108
+ If you would like direct, low-level control of attribute serialization, you can
109
+ completely override the attributes method to return the hash you need:
110
+
111
+ ```ruby
112
+ require "json_serializer"
113
+
114
+ class UserSerializer < JsonSerializer
115
+ attribute :id
116
+ attribute :first_name
117
+ attribute :last_name
118
+
119
+ attr :scope
120
+
121
+ def initialize(object, scope)
122
+ super(object)
123
+ @scope = scope
124
+ end
125
+
126
+ def attributes
127
+ hash = super
128
+ hash.merge!(admin: object.admin) if scope.admin?
129
+ hash
130
+ end
131
+ end
132
+ ```
133
+
134
+ ### Attributes with Custom Serializer
135
+
136
+ You can specify a serializer class for a defined attribute. This is very useful
137
+ for serializing each element of an association.
138
+
139
+ ```ruby
140
+ require "json_serializer"
141
+
142
+ class UserSerializer < JsonSerializer
143
+ attribute :id
144
+ attribute :username
145
+ end
146
+
147
+ class PostSerializer < JsonSerializer
148
+ attribute :id
149
+ attribute :title
150
+ attribute :user, :UserSerializer
151
+ attribute :comments, :CommentSerializer
152
+ end
153
+
154
+ class CommentSerializer < JsonSerializer
155
+ attribute :id
156
+ attribute :content
157
+ attribute :user, :UserSerializer
158
+ end
159
+
160
+ admin = User.create(username: "admin", admin: true)
161
+ user = User.create(username: "user")
162
+
163
+ post = Post.create(title: "Hello!", user: admin)
164
+ post.comments << Comment.create(content: "First comment", user: user)
165
+
166
+ PostSerializer.new(post).to_json
167
+ ```
168
+
169
+ The example above returns the following json output:
170
+
171
+ ```json
172
+ {
173
+ "id": 1,
174
+ "title": "Hello!",
175
+ "user":
176
+ {
177
+ "id": 1,
178
+ "username": "admin"
179
+ },
180
+ "comments":
181
+ [
182
+ {
183
+ "id": 1,
184
+ "content": "First comment",
185
+ "user":
186
+ {
187
+ "id": 2,
188
+ "username": "user"
189
+ }
190
+ }
191
+ ]
192
+ }
193
+ ```
194
+
195
+ [active_model_serializers]: https://github.com/rails-api/active_model_serializers
@@ -0,0 +1,24 @@
1
+ This is free and unencumbered software released into the public domain.
2
+
3
+ Anyone is free to copy, modify, publish, use, compile, sell, or
4
+ distribute this software, either in source code form or as a compiled
5
+ binary, for any purpose, commercial or non-commercial, and by any
6
+ means.
7
+
8
+ In jurisdictions that recognize copyright laws, the author or authors
9
+ of this software dedicate any and all copyright interest in the
10
+ software to the public domain. We make this dedication for the benefit
11
+ of the public at large and to the detriment of our heirs and
12
+ successors. We intend this dedication to be an overt act of
13
+ relinquishment in perpetuity of all present and future rights to this
14
+ software under copyright law.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19
+ IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20
+ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22
+ OTHER DEALINGS IN THE SOFTWARE.
23
+
24
+ For more information, please refer to <http://unlicense.org/>
@@ -1,22 +1,14 @@
1
- # encoding: utf-8
2
-
3
1
  Gem::Specification.new do |s|
4
- s.name = 'json-serializer'
5
- s.version = '0.0.2'
6
- s.summary = 'Replaces hash-driven development with object-oriented development'
2
+ s.name = "json-serializer"
3
+ s.version = "0.0.3"
4
+ s.summary = "Customize JSON ouput through serializer objects."
7
5
  s.description = s.summary
8
- s.authors = ['Francesco Rodríguez']
9
- s.email = ['lrodriguezsanc@gmail.com']
10
- s.homepage = 'https://github.com/frodsan/mocoso'
11
- s.license = 'MIT'
6
+ s.authors = ["Francesco Rodríguez"]
7
+ s.email = ["lrodriguezsanc@gmail.com"]
8
+ s.homepage = "https://github.com/frodsan/mocoso"
9
+ s.license = "Unlicense"
12
10
 
13
- s.files = Dir[
14
- 'LICENSE',
15
- 'README.md',
16
- 'lib/**/*.rb',
17
- '*.gemspec',
18
- 'test/*.*'
19
- ]
11
+ s.files = `git ls-files`.split("\n")
20
12
 
21
- s.add_development_dependency 'cutest'
13
+ s.add_development_dependency "cutest"
22
14
  end
@@ -1,64 +1,21 @@
1
- require 'json'
1
+ require "json"
2
2
 
3
3
  class JsonSerializer
4
- # Specify which attributes you would like to include in the outputted JSON.
5
- #
6
- # class UserSerializer < JsonSerializer
7
- # attribute :id
8
- # attribute :username
9
- # end
10
- #
11
- # user = User.create username: 'skrillex', admin: true
12
- #
13
- # UserSerializer.new(user).to_json
14
- # # => {"id":1,"username":"skrillex"}
15
- #
16
- # By default, before looking up the attribute on the object, checks the presence
17
- # of a method with the attribute name. This allow serializers to include properties
18
- # in addition to the object attributes or customize the result of a specified
19
- # attribute. You can access the object being serialized with the +object+ method.
20
- #
21
- # class UserSerializer < JsonSerializer
22
- # attribute :id
23
- # attribute :username
24
- # attribute :full_name
25
- #
26
- # def full_name
27
- # object.first_name + ' ' + object.last_name
28
- # end
29
- # end
30
- #
31
- # user = User.create username: 'skrillex', first_name: 'sonny', last_name: 'moore'
32
- #
33
- # UserSerializer.new(user).to_json
34
- # # => {"id":1,"username":"skrillex","full_name":"sonny moore"}
35
- #
36
- def self.attribute name, serializer = nil
4
+ def self.attribute(name, serializer = nil)
37
5
  attributes[name] ||= serializer
38
6
  end
39
7
 
40
- # Return an array with the specified attributes by +attribute+.
41
- #
42
- # class UserSerializer < JsonSerializer
43
- # attribute :id
44
- # attribute :username
45
- # attribute :github
46
- # end
47
- #
48
- # UserSerializer.attributes
49
- # # => [:id, :username, :github]
50
- #
51
8
  def self.attributes
52
9
  @attributes ||= {}
53
10
  end
54
11
 
55
12
  attr :object
56
13
 
57
- def initialize object
14
+ def initialize(object)
58
15
  @object = object
59
16
  end
60
17
 
61
- def to_json options={}
18
+ def to_json(options={})
62
19
  if root = options[:root]
63
20
  { root => serializable_object }.to_json
64
21
  else
@@ -66,20 +23,31 @@ class JsonSerializer
66
23
  end
67
24
  end
68
25
 
69
- def serializable_object # :nodoc:
26
+ protected
27
+
28
+ def serializable_object
70
29
  if object.respond_to?(:to_ary)
71
30
  object.to_ary.map { |item| self.class.new(item).attributes }
72
31
  else
73
32
  attributes
74
33
  end
75
34
  end
76
- protected :serializable_object
77
35
 
78
- def attributes # :nodoc:
36
+ def attributes
79
37
  self.class.attributes.each_with_object({}) do |(name, serializer), hash|
80
38
  data = self.class.method_defined?(name) ? self.send(name) : object.send(name)
81
- data = serializer.new(data).serializable_object if serializer
39
+ data = Utils.const(self.class, serializer).new(data).serializable_object if serializer
82
40
  hash[name] = data
83
41
  end
84
42
  end
43
+
44
+ module Utils
45
+ def self.const(context, name)
46
+ case name
47
+ when Symbol, String
48
+ context.const_get(name)
49
+ else name
50
+ end
51
+ end
52
+ end
85
53
  end
@@ -1 +1 @@
1
- require 'json-serializer'
1
+ require_relative 'json-serializer'
@@ -0,0 +1,4 @@
1
+ .PHONY: test
2
+
3
+ test:
4
+ cutest test/*.rb
@@ -0,0 +1,155 @@
1
+ require_relative "helper"
2
+
3
+ User = OpenStruct
4
+ Organization = OpenStruct
5
+
6
+ class OrganizationSerializer < JsonSerializer
7
+ attribute :id
8
+ attribute :name
9
+ end
10
+
11
+ class UserWithOrganizationSerializer < JsonSerializer
12
+ attribute :id
13
+ attribute :name
14
+ attribute :organization, :OrganizationSerializer
15
+ end
16
+
17
+ test "serializes object with association" do
18
+ user = User.new(id: 1, name: "sonny")
19
+ user.organization = Organization.new(id: 1, name: "enterprise")
20
+
21
+ result = {
22
+ id: 1,
23
+ name: "sonny",
24
+ organization: {
25
+ id: 1,
26
+ name: "enterprise"
27
+ }
28
+ }.to_json
29
+
30
+ assert_equal result, UserWithOrganizationSerializer.new(user).to_json
31
+ end
32
+
33
+ test "serializes array with association" do
34
+ users = [
35
+ User.new(id: 1, name: "sonny", organization: Organization.new(id: 1, name: "enterprise")),
36
+ User.new(id: 2, name: "anton", organization: Organization.new(id: 2, name: "evil"))
37
+ ]
38
+
39
+ result = [
40
+ {
41
+ id: 1,
42
+ name: "sonny",
43
+ organization: {
44
+ id: 1,
45
+ name: "enterprise"
46
+ }
47
+ },
48
+ {
49
+ id: 2,
50
+ name: "anton",
51
+ organization: {
52
+ id: 2,
53
+ name: "evil"
54
+ }
55
+ }
56
+ ].to_json
57
+
58
+ assert_equal result, UserWithOrganizationSerializer.new(users).to_json
59
+ end
60
+
61
+ class UserWithOrganizationsSerializer < JsonSerializer
62
+ attribute :id
63
+ attribute :name
64
+ attribute :organizations, :OrganizationSerializer
65
+ end
66
+
67
+ test "serializes object with collection" do
68
+ user = User.new(id: 1, name: "sonny")
69
+ user.organizations = [
70
+ Organization.new(id: 1, name: "enterprise"),
71
+ Organization.new(id: 2, name: "evil")
72
+ ]
73
+
74
+ result = {
75
+ id: 1,
76
+ name: "sonny",
77
+ organizations: [
78
+ {
79
+ id: 1,
80
+ name: "enterprise"
81
+ },
82
+ {
83
+ id: 2,
84
+ name: "evil"
85
+ }
86
+ ]
87
+ }.to_json
88
+
89
+ assert_equal result, UserWithOrganizationsSerializer.new(user).to_json
90
+ end
91
+
92
+ test "serializes array with nested collections" do
93
+ users = [
94
+ User.new(
95
+ id: 1,
96
+ name: "sonny",
97
+ organizations: [
98
+ Organization.new(id: 1, name: "enterprise"),
99
+ Organization.new(id: 2, name: "evil"),
100
+ ]
101
+ ),
102
+ User.new(
103
+ id: 2,
104
+ name: "anton",
105
+ organizations: [
106
+ Organization.new(id: 3, name: "showtek")
107
+ ]
108
+ )
109
+ ]
110
+
111
+ result = [
112
+ {
113
+ id: 1,
114
+ name: "sonny",
115
+ organizations: [
116
+ {
117
+ id: 1,
118
+ name: "enterprise"
119
+ },
120
+ {
121
+ id: 2,
122
+ name: "evil"
123
+ }
124
+ ]
125
+ },
126
+ {
127
+ id: 2,
128
+ name: "anton",
129
+ organizations: [
130
+ {
131
+ id: 3,
132
+ name: "showtek"
133
+ }
134
+ ]
135
+ }
136
+ ].to_json
137
+
138
+ assert_equal result, UserWithOrganizationsSerializer.new(users).to_json
139
+ end
140
+
141
+ class UserWithCustomOrganizationSerializer < JsonSerializer
142
+ attribute :organizations, :OrganizationSerializer
143
+
144
+ def organizations
145
+ [Organization.new(id: 1, name: "enterprise")]
146
+ end
147
+ end
148
+
149
+ test "implements association method and returns different result" do
150
+ user = User.new
151
+
152
+ result = { organizations: [ { id: 1, name: "enterprise" } ] }.to_json
153
+
154
+ assert_equal result, UserWithCustomOrganizationSerializer.new(user).to_json
155
+ end
@@ -0,0 +1,49 @@
1
+ require_relative "helper"
2
+
3
+ Post = OpenStruct
4
+ User = OpenStruct
5
+
6
+ class PostSerializer < JsonSerializer
7
+ attribute :id
8
+ attribute :title
9
+ attribute :slug
10
+
11
+ def slug
12
+ "#{ object.id }-#{ object.title }"
13
+ end
14
+ end
15
+
16
+ test "converts defined attributes into json" do
17
+ post = Post.new(id: 1, title: "tsunami")
18
+
19
+ result = {
20
+ id: 1,
21
+ title: "tsunami",
22
+ slug: "1-tsunami"
23
+ }.to_json
24
+
25
+ assert_equal result, PostSerializer.new(post).to_json
26
+ end
27
+
28
+ class UserSerializer < JsonSerializer
29
+ attribute :id
30
+ attribute :fullname
31
+
32
+ def fullname
33
+ object.name + " " + object.lastname
34
+ end
35
+ end
36
+
37
+ test "serializes array" do
38
+ users = [
39
+ User.new(id: 1, name: "sonny", lastname: "moore"),
40
+ User.new(id: 2, name: "anton", lastname: "zaslavski")
41
+ ]
42
+
43
+ result = [
44
+ { id: 1, fullname: "sonny moore" },
45
+ { id: 2, fullname: "anton zaslavski" }
46
+ ].to_json
47
+
48
+ assert_equal result, UserSerializer.new(users).to_json
49
+ end
@@ -0,0 +1,3 @@
1
+ require "cutest"
2
+ require_relative "../lib/json_serializer"
3
+ require "ostruct"
@@ -0,0 +1,23 @@
1
+ require_relative "helper"
2
+
3
+ Person = OpenStruct
4
+
5
+ class PersonSerializer < JsonSerializer
6
+ attribute :name
7
+ end
8
+
9
+ setup do
10
+ Person.new(name: "sonny")
11
+ end
12
+
13
+ test "serialized object includes root" do |person|
14
+ result = { person: person.to_h }.to_json
15
+
16
+ assert_equal result, PersonSerializer.new(person).to_json(root: :person)
17
+ end
18
+
19
+ test "serialized array includes root" do |person|
20
+ result = { people: [person.to_h] }.to_json
21
+
22
+ assert_equal result, PersonSerializer.new([person]).to_json(root: :people)
23
+ end
metadata CHANGED
@@ -1,45 +1,50 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: json-serializer
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.0.2
4
+ version: 0.0.3
5
5
  platform: ruby
6
6
  authors:
7
7
  - Francesco Rodríguez
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2013-11-19 00:00:00.000000000 Z
11
+ date: 2014-01-05 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: cutest
15
15
  requirement: !ruby/object:Gem::Requirement
16
16
  requirements:
17
- - - '>='
17
+ - - ">="
18
18
  - !ruby/object:Gem::Version
19
19
  version: '0'
20
20
  type: :development
21
21
  prerelease: false
22
22
  version_requirements: !ruby/object:Gem::Requirement
23
23
  requirements:
24
- - - '>='
24
+ - - ">="
25
25
  - !ruby/object:Gem::Version
26
26
  version: '0'
27
- description: Replaces hash-driven development with object-oriented development
27
+ description: Customize JSON ouput through serializer objects.
28
28
  email:
29
29
  - lrodriguezsanc@gmail.com
30
30
  executables: []
31
31
  extensions: []
32
32
  extra_rdoc_files: []
33
33
  files:
34
- - LICENSE
34
+ - ".gems"
35
35
  - README.md
36
+ - UNLICENSE
37
+ - json-serializer.gemspec
36
38
  - lib/json-serializer.rb
37
39
  - lib/json_serializer.rb
38
- - json-serializer.gemspec
39
- - test/json_serializer_test.rb
40
+ - makefile
41
+ - test/association.rb
42
+ - test/attribute.rb
43
+ - test/helper.rb
44
+ - test/root.rb
40
45
  homepage: https://github.com/frodsan/mocoso
41
46
  licenses:
42
- - MIT
47
+ - Unlicense
43
48
  metadata: {}
44
49
  post_install_message:
45
50
  rdoc_options: []
@@ -47,18 +52,18 @@ require_paths:
47
52
  - lib
48
53
  required_ruby_version: !ruby/object:Gem::Requirement
49
54
  requirements:
50
- - - '>='
55
+ - - ">="
51
56
  - !ruby/object:Gem::Version
52
57
  version: '0'
53
58
  required_rubygems_version: !ruby/object:Gem::Requirement
54
59
  requirements:
55
- - - '>='
60
+ - - ">="
56
61
  - !ruby/object:Gem::Version
57
62
  version: '0'
58
63
  requirements: []
59
64
  rubyforge_project:
60
- rubygems_version: 2.0.3
65
+ rubygems_version: 2.2.0
61
66
  signing_key:
62
67
  specification_version: 4
63
- summary: Replaces hash-driven development with object-oriented development
68
+ summary: Customize JSON ouput through serializer objects.
64
69
  test_files: []
data/LICENSE DELETED
@@ -1,19 +0,0 @@
1
- Copyright (c) 2013 Francesco Rodríguez
2
-
3
- Permission is hereby granted, free of charge, to any person obtaining a copy
4
- of this software and associated documentation files (the "Software"), to deal
5
- in the Software without restriction, including without limitation the rights
6
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
- copies of the Software, and to permit persons to whom the Software is
8
- furnished to do so, subject to the following conditions:
9
-
10
- The above copyright notice and this permission notice shall be included in
11
- all copies or substantial portions of the Software.
12
-
13
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19
- THE SOFTWARE.
@@ -1,230 +0,0 @@
1
- require 'cutest'
2
- require_relative '../lib/json-serializer'
3
-
4
- Post = Struct.new :id, :title, :created_at
5
-
6
- class PostSerializer < JsonSerializer
7
- attribute :id
8
- attribute :title
9
- attribute :slug
10
-
11
- def slug
12
- "#{ object.id }-#{ object.title }"
13
- end
14
- end
15
-
16
- test 'converts defined attributes into json' do
17
- post = Post.new 1, 'tsunami'
18
-
19
- result = {
20
- id: 1,
21
- title: 'tsunami',
22
- slug: '1-tsunami'
23
- }
24
-
25
- assert_equal result.to_json, PostSerializer.new(post).to_json
26
- end
27
-
28
- class User
29
- attr_accessor :id, :name, :lastname, :organization, :organizations
30
-
31
- def initialize attrs={}
32
- attrs.each do |name, value|
33
- send "#{name}=", value
34
- end
35
- end
36
- end
37
-
38
- class UserSerializer < JsonSerializer
39
- attribute :id
40
- attribute :fullname
41
-
42
- def fullname
43
- object.name + ' ' + object.lastname
44
- end
45
- end
46
-
47
- test 'serializes array' do
48
- users = [
49
- User.new(id: 1, name: 'sonny', lastname: 'moore'),
50
- User.new(id: 2, name: 'anton', lastname: 'zaslavski')
51
- ]
52
-
53
- result = [
54
- { id: 1, fullname: 'sonny moore' },
55
- { id: 2, fullname: 'anton zaslavski' }
56
- ].to_json
57
-
58
- assert_equal result, UserSerializer.new(users).to_json
59
- end
60
-
61
- Organization = Struct.new :id, :name, :created_at
62
-
63
- class OrganizationSerializer < JsonSerializer
64
- attribute :id
65
- attribute :name
66
- end
67
-
68
- class UserWithOrganizationSerializer < JsonSerializer
69
- attribute :id
70
- attribute :name
71
- attribute :organization, OrganizationSerializer
72
- end
73
-
74
- test 'serializes object with association' do
75
- user = User.new id: 1, name: 'sonny'
76
- user.organization = Organization.new 1, 'enterprise'
77
-
78
- result = {
79
- id: 1,
80
- name: 'sonny',
81
- organization: {
82
- id: 1,
83
- name: 'enterprise'
84
- }
85
- }.to_json
86
-
87
- assert_equal result, UserWithOrganizationSerializer.new(user).to_json
88
- end
89
-
90
- test 'serializes array with association' do
91
- users = [
92
- User.new(id: 1, name: 'sonny', organization: Organization.new(1, 'enterprise')),
93
- User.new(id: 2, name: 'anton', organization: Organization.new(2, 'evil'))
94
- ]
95
-
96
- result = [
97
- {
98
- id: 1,
99
- name: 'sonny',
100
- organization: {
101
- id: 1,
102
- name: 'enterprise'
103
- }
104
- },
105
- {
106
- id: 2,
107
- name: 'anton',
108
- organization: {
109
- id: 2,
110
- name: 'evil'
111
- }
112
- }
113
- ].to_json
114
-
115
- assert_equal result, UserWithOrganizationSerializer.new(users).to_json
116
- end
117
-
118
- class UserWithOrganizationsSerializer < JsonSerializer
119
- attribute :id
120
- attribute :name
121
- attribute :organizations, OrganizationSerializer
122
- end
123
-
124
- test 'serializes object with collection' do
125
- user = User.new id: 1, name: 'sonny'
126
- user.organizations = [
127
- Organization.new(1, 'enterprise'),
128
- Organization.new(2, 'evil')
129
- ]
130
-
131
- result = {
132
- id: 1,
133
- name: 'sonny',
134
- organizations: [
135
- {
136
- id: 1,
137
- name: 'enterprise'
138
- },
139
- {
140
- id: 2,
141
- name: 'evil'
142
- }
143
- ]
144
- }.to_json
145
-
146
- assert_equal result, UserWithOrganizationsSerializer.new(user).to_json
147
- end
148
-
149
- test 'serializes array with nested collections' do
150
- users = [
151
- User.new(
152
- id: 1,
153
- name: 'sonny',
154
- organizations: [
155
- Organization.new(1, 'enterprise'),
156
- Organization.new(2, 'evil'),
157
- ]
158
- ),
159
- User.new(
160
- id: 2,
161
- name: 'anton',
162
- organizations: [
163
- Organization.new(3, 'showtek')
164
- ]
165
- )
166
- ]
167
-
168
- result = [
169
- {
170
- id: 1,
171
- name: 'sonny',
172
- organizations: [
173
- {
174
- id: 1,
175
- name: 'enterprise'
176
- },
177
- {
178
- id: 2,
179
- name: 'evil'
180
- }
181
- ]
182
- },
183
- {
184
- id: 2,
185
- name: 'anton',
186
- organizations: [
187
- {
188
- id: 3,
189
- name: 'showtek'
190
- }
191
- ]
192
- }
193
- ].to_json
194
-
195
- assert_equal result, UserWithOrganizationsSerializer.new(users).to_json
196
- end
197
-
198
- class UserWithCustomOrganizationSerializer < JsonSerializer
199
- attribute :organizations, OrganizationSerializer
200
-
201
- def organizations
202
- [ Organization.new(1, 'enterprise') ]
203
- end
204
- end
205
-
206
- test 'implements association method and returns different result' do
207
- user = User.new
208
-
209
- result = { organizations: [ { id: 1, name: 'enterprise' } ] }.to_json
210
-
211
- assert_equal result, UserWithCustomOrganizationSerializer.new(user).to_json
212
- end
213
-
214
- Person = Struct.new :name
215
-
216
- class PersonSerialize < JsonSerializer
217
- attribute :name
218
- end
219
-
220
- test 'allows root option' do
221
- person = Person.new 'sonny'
222
-
223
- result = { person: person.to_h }.to_json
224
-
225
- assert_equal result, PersonSerialize.new(person).to_json(root: :person)
226
-
227
- result = { people: [person.to_h] }.to_json
228
-
229
- assert_equal result, PersonSerialize.new([person]).to_json(root: :people)
230
- end