Skip to content

Commit dd2081d

Browse files
committed
Add Model#attributes helper; make test attributes explicit
1 parent 85dfef9 commit dd2081d

30 files changed

+514
-296
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,14 @@ Breaking changes:
66

77
Features:
88

9+
- [#2021](https://github.com/rails-api/active_model_serializers/pull/2021) ActiveModelSerializers::Model#attributes. (@bf4)
10+
911
Fixes:
1012

1113
Misc:
1214

15+
- [#2021](https://github.com/rails-api/active_model_serializers/pull/2021) Make test attributes explicit. Tests have Model#associations. (@bf4)
16+
1317
### [v0.10.4 (2017-01-06)](https://github.com/rails-api/active_model_serializers/compare/v0.10.3...v0.10.4)
1418

1519
Misc:

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ class SomeResource < ActiveRecord::Base
116116
end
117117
# or
118118
class SomeResource < ActiveModelSerializers::Model
119-
attr_accessor :title, :body
119+
attributes :title, :body
120120
end
121121
```
122122

@@ -279,7 +279,7 @@ which is a simple serializable PORO (Plain-Old Ruby Object).
279279

280280
```ruby
281281
class MyModel < ActiveModelSerializers::Model
282-
attr_accessor :id, :name, :level
282+
attributes :id, :name, :level
283283
end
284284
```
285285

docs/howto/serialize_poro.md

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,16 @@
22

33
# How to serialize a Plain-Old Ruby Object (PORO)
44

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+
When you are first getting started with ActiveModelSerializers, it may seem only `ActiveRecord::Base` objects can be serializable,
6+
but pretty much any object can be serializable with ActiveModelSerializers.
7+
Here is an example of a PORO that is serializable in most situations:
8+
69
```ruby
710
# my_model.rb
811
class MyModel
912
alias :read_attribute_for_serialization :send
1013
attr_accessor :id, :name, :level
11-
14+
1215
def initialize(attributes)
1316
@id = attributes[:id]
1417
@name = attributes[:name]
@@ -21,12 +24,22 @@ class MyModel
2124
end
2225
```
2326

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+
The [ActiveModel::Serializer::Lint::Tests](../../lib/active_model/serializer/lint.rb)
28+
define and validate which methods ActiveModelSerializers expects to be implemented.
29+
30+
An implementation of the complete spec is included either for use or as reference:
31+
[`ActiveModelSerializers::Model`](../../lib/active_model_serializers/model.rb).
32+
You can use in production code that will make your PORO a lot cleaner.
33+
34+
The above code now becomes:
35+
2536
```ruby
2637
# my_model.rb
2738
class MyModel < ActiveModelSerializers::Model
28-
attr_accessor :id, :name, :level
39+
attributes :id, :name, :level
2940
end
3041
```
3142

32-
The default serializer would be `MyModelSerializer`.
43+
The default serializer would be `MyModelSerializer`.
44+
45+
For more information, see [README: What does a 'serializable resource' look like?](../../README.md#what-does-a-serializable-resource-look-like).

lib/active_model_serializers.rb

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,14 @@ def self.default_include_directive
3838
@default_include_directive ||= JSONAPI::IncludeDirective.new(config.default_includes, allow_wildcard: true)
3939
end
4040

41+
def self.silence_warnings
42+
original_verbose = $VERBOSE
43+
$VERBOSE = nil
44+
yield
45+
ensure
46+
$VERBOSE = original_verbose
47+
end
48+
4149
require 'active_model/serializer/version'
4250
require 'active_model/serializer'
4351
require 'active_model/serializable_resource'

lib/active_model_serializers/model.rb

Lines changed: 74 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,94 @@
1-
# ActiveModelSerializers::Model is a convenient
2-
# serializable class to inherit from when making
3-
# serializable non-activerecord objects.
1+
# ActiveModelSerializers::Model is a convenient superclass for making your models
2+
# from Plain-Old Ruby Objects (PORO). It also serves as a reference implementation
3+
# that satisfies ActiveModel::Serializer::Lint::Tests.
44
module ActiveModelSerializers
55
class Model
6-
include ActiveModel::Model
76
include ActiveModel::Serializers::JSON
7+
include ActiveModel::Model
8+
9+
# Easily declare instance attributes with setters and getters for each.
10+
#
11+
# All attributes to initialize an instance must have setters.
12+
# However, the hash turned by +attributes+ instance method will ALWAYS
13+
# be the value of the initial attributes, regardless of what accessors are defined.
14+
# The only way to change the change the attributes after initialization is
15+
# to mutate the +attributes+ directly.
16+
# Accessor methods do NOT mutate the attributes. (This is a bug).
17+
#
18+
# @note For now, the Model only supports the notion of 'attributes'.
19+
# In the tests, there is a special Model that also supports 'associations'. This is
20+
# important so that we can add accessors for values that should not appear in the
21+
# attributes hash when modeling associations. It is not yet clear if it
22+
# makes sense for a PORO to have associations outside of the tests.
23+
#
24+
# @overload attributes(names)
25+
# @param names [Array<String, Symbol>]
26+
# @param name [String, Symbol]
27+
def self.attributes(*names)
28+
# Silence redefinition of methods warnings
29+
ActiveModelSerializers.silence_warnings do
30+
attr_accessor(*names)
31+
end
32+
end
33+
34+
# Support for validation and other ActiveModel::Errors
35+
# @return [ActiveModel::Errors]
36+
attr_reader :errors
837

9-
attr_reader :attributes, :errors
38+
# (see #updated_at)
39+
attr_writer :updated_at
1040

41+
# @param attributes [Hash]
1142
def initialize(attributes = {})
12-
@attributes = attributes && attributes.symbolize_keys
43+
attributes ||= {} # protect against nil
44+
@attributes = attributes.symbolize_keys.with_indifferent_access
1345
@errors = ActiveModel::Errors.new(self)
1446
super
1547
end
1648

17-
# Defaults to the downcased model name.
18-
def id
19-
attributes.fetch(:id) { self.class.name.downcase }
49+
# The only way to change the attributes of an instance is to directly mutate the attributes.
50+
# @example
51+
#
52+
# model.attributes[:foo] = :bar
53+
# @return [Hash]
54+
def attributes
55+
instance_variable_get(:@attributes)
2056
end
2157

22-
# Defaults to the downcased model name and updated_at
23-
def cache_key
24-
attributes.fetch(:cache_key) { "#{self.class.name.downcase}/#{id}-#{updated_at.strftime('%Y%m%d%H%M%S%9N')}" }
58+
# Defaults to the downcased model name.
59+
# This probably isn't a good default, since it's not a unique instance identifier,
60+
# but that's what is currently implemented \_('-')_/.
61+
#
62+
# @note Though +id+ is defined, it will only show up
63+
# in +attributes+ when it is passed in to the initializer or added to +attributes+,
64+
# such as <tt>attributes[:id] = 5</tt>.
65+
# @return [String, Numeric, Symbol]
66+
def id
67+
instance_variable_get(:@attributes).fetch(:id) do
68+
defined?(@id) ? @id : self.class.model_name.name && self.class.model_name.name.downcase
69+
end
2570
end
2671

27-
# Defaults to the time the serializer file was modified.
72+
# When not set, defaults to the time the file was modified.
73+
#
74+
# @note Though +updated_at+ and +updated_at=+ are defined, it will only show up
75+
# in +attributes+ when it is passed in to the initializer or added to +attributes+,
76+
# such as <tt>attributes[:updated_at] = Time.current</tt>.
77+
# @return [String, Numeric, Time]
2878
def updated_at
29-
attributes.fetch(:updated_at) { File.mtime(__FILE__) }
79+
instance_variable_get(:@attributes).fetch(:updated_at) do
80+
defined?(@updated_at) ? @updated_at : File.mtime(__FILE__)
81+
end
3082
end
3183

32-
def read_attribute_for_serialization(key)
33-
if key == :id || key == 'id'
34-
attributes.fetch(key) { id }
35-
else
36-
attributes[key]
37-
end
84+
# To customize model behavior, this method must be redefined. However,
85+
# there are other ways of setting the +cache_key+ a serializer uses.
86+
# @return [String]
87+
def cache_key
88+
ActiveSupport::Cache.expand_cache_key([
89+
self.class.model_name.name.downcase,
90+
"#{id}-#{updated_at.strftime('%Y%m%d%H%M%S%9N')}"
91+
].compact)
3892
end
3993

4094
# The following methods are needed to be minimally implemented for ActiveModel::Errors

test/action_controller/adapter_selector_test.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ def render_using_adapter_override
1515
end
1616

1717
def render_skipping_adapter
18-
@profile = Profile.new(name: 'Name 1', description: 'Description 1', comments: 'Comments 1')
18+
@profile = Profile.new(id: 'render_skipping_adapter_id', name: 'Name 1', description: 'Description 1', comments: 'Comments 1')
1919
render json: @profile, adapter: false
2020
end
2121
end
@@ -46,7 +46,7 @@ def test_render_using_adapter_override
4646

4747
def test_render_skipping_adapter
4848
get :render_skipping_adapter
49-
assert_equal '{"name":"Name 1","description":"Description 1","comments":"Comments 1"}', response.body
49+
assert_equal '{"id":"render_skipping_adapter_id","name":"Name 1","description":"Description 1"}', response.body
5050
end
5151
end
5252
end

test/action_controller/json_api/fields_test.rb

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,16 @@ module Serialization
55
class JsonApi
66
class FieldsTest < ActionController::TestCase
77
class FieldsTestController < ActionController::Base
8-
class PostSerializer < ActiveModel::Serializer
8+
class AuthorWithName < Author
9+
attributes :first_name, :last_name
10+
end
11+
class AuthorWithNameSerializer < AuthorSerializer
12+
type 'authors'
13+
end
14+
class PostWithPublishAt < Post
15+
attributes :publish_at
16+
end
17+
class PostWithPublishAtSerializer < ActiveModel::Serializer
918
type 'posts'
1019
attributes :title, :body, :publish_at
1120
belongs_to :author
@@ -14,19 +23,19 @@ class PostSerializer < ActiveModel::Serializer
1423

1524
def setup_post
1625
ActionController::Base.cache_store.clear
17-
@author = Author.new(id: 1, first_name: 'Bob', last_name: 'Jones')
26+
@author = AuthorWithName.new(id: 1, first_name: 'Bob', last_name: 'Jones')
1827
@comment1 = Comment.new(id: 7, body: 'cool', author: @author)
1928
@comment2 = Comment.new(id: 12, body: 'awesome', author: @author)
20-
@post = Post.new(id: 1337, title: 'Title 1', body: 'Body 1',
21-
author: @author, comments: [@comment1, @comment2],
22-
publish_at: '2020-03-16T03:55:25.291Z')
29+
@post = PostWithPublishAt.new(id: 1337, title: 'Title 1', body: 'Body 1',
30+
author: @author, comments: [@comment1, @comment2],
31+
publish_at: '2020-03-16T03:55:25.291Z')
2332
@comment1.post = @post
2433
@comment2.post = @post
2534
end
2635

2736
def render_fields_works_on_relationships
2837
setup_post
29-
render json: @post, serializer: PostSerializer, adapter: :json_api, fields: { posts: [:author] }
38+
render json: @post, serializer: PostWithPublishAtSerializer, adapter: :json_api, fields: { posts: [:author] }
3039
end
3140
end
3241

test/action_controller/json_api/transform_test.rb

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,17 @@ module Serialization
55
class JsonApi
66
class KeyTransformTest < ActionController::TestCase
77
class KeyTransformTestController < ActionController::Base
8-
class Post < ::Model; end
9-
class Author < ::Model; end
10-
class TopComment < ::Model; end
8+
class Post < ::Model
9+
attributes :title, :body, :publish_at
10+
associations :author, :top_comments
11+
end
12+
class Author < ::Model
13+
attributes :first_name, :last_name
14+
end
15+
class TopComment < ::Model
16+
attributes :body
17+
associations :author, :post
18+
end
1119
class PostSerializer < ActiveModel::Serializer
1220
type 'posts'
1321
attributes :title, :body, :publish_at

test/action_controller/namespace_lookup_test.rb

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,16 @@
33
module ActionController
44
module Serialization
55
class NamespaceLookupTest < ActionController::TestCase
6-
class Book < ::Model; end
7-
class Page < ::Model; end
8-
class Chapter < ::Model; end
9-
class Writer < ::Model; end
6+
class Book < ::Model
7+
attributes :title, :body
8+
associations :writer, :chapters
9+
end
10+
class Chapter < ::Model
11+
attributes :title
12+
end
13+
class Writer < ::Model
14+
attributes :name
15+
end
1016

1117
module Api
1218
module V2
@@ -93,7 +99,7 @@ def explicit_namespace_as_symbol
9399
end
94100

95101
def invalid_namespace
96-
book = Book.new(title: 'New Post', body: 'Body')
102+
book = Book.new(id: 'invalid_namespace_book_id', title: 'New Post', body: 'Body')
97103

98104
render json: book, namespace: :api_v2
99105
end
@@ -205,7 +211,7 @@ def namespace_set_by_request_headers
205211

206212
assert_serializer ActiveModel::Serializer::Null
207213

208-
expected = { 'title' => 'New Post', 'body' => 'Body' }
214+
expected = { 'id' => 'invalid_namespace_book_id', 'title' => 'New Post', 'body' => 'Body' }
209215
actual = JSON.parse(@response.body)
210216

211217
assert_equal expected, actual

test/action_controller/serialization_scope_name_test.rb

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,16 @@
22

33
module SerializationScopeTesting
44
class User < ActiveModelSerializers::Model
5-
attr_accessor :id, :name, :admin
5+
attributes :id, :name, :admin
66
def admin?
77
admin
88
end
99
end
1010
class Comment < ActiveModelSerializers::Model
11-
attr_accessor :id, :body
11+
attributes :id, :body
1212
end
1313
class Post < ActiveModelSerializers::Model
14-
attr_accessor :id, :title, :body, :comments
14+
attributes :id, :title, :body, :comments
1515
end
1616
class PostSerializer < ActiveModel::Serializer
1717
attributes :id, :title, :body, :comments

test/action_controller/serialization_test.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,7 @@ def render_fragment_changed_object_with_relationship
135135
like = Like.new(id: 1, likeable: comment, time: 3.days.ago)
136136

137137
generate_cached_serializer(like)
138-
like.likable = comment2
138+
like.likeable = comment2
139139
like.time = Time.zone.now.to_s
140140

141141
render json: like

0 commit comments

Comments
 (0)