Merge pull request #2021 from bf4/make_tests_explicit

Add Model#attributes helper; make test attributes explicit
This commit is contained in:
Benjamin Fleischer 2017-01-08 16:37:53 -05:00 committed by GitHub
commit 4e6bd61350
30 changed files with 524 additions and 308 deletions

View File

@ -6,10 +6,14 @@ Breaking changes:
Features: Features:
- [#2021](https://github.com/rails-api/active_model_serializers/pull/2021) ActiveModelSerializers::Model#attributes. (@bf4)
Fixes: Fixes:
Misc: Misc:
- [#2021](https://github.com/rails-api/active_model_serializers/pull/2021) Make test attributes explicit. Tests have Model#associations. (@bf4)
### [v0.10.4 (2017-01-06)](https://github.com/rails-api/active_model_serializers/compare/v0.10.3...v0.10.4) ### [v0.10.4 (2017-01-06)](https://github.com/rails-api/active_model_serializers/compare/v0.10.3...v0.10.4)
Misc: Misc:

View File

@ -116,7 +116,7 @@ class SomeResource < ActiveRecord::Base
end end
# or # or
class SomeResource < ActiveModelSerializers::Model class SomeResource < ActiveModelSerializers::Model
attr_accessor :title, :body attributes :title, :body
end end
``` ```
@ -279,7 +279,7 @@ which is a simple serializable PORO (Plain-Old Ruby Object).
```ruby ```ruby
class MyModel < ActiveModelSerializers::Model class MyModel < ActiveModelSerializers::Model
attr_accessor :id, :name, :level attributes :id, :name, :level
end end
``` ```

View File

@ -2,13 +2,16 @@
# How to serialize a Plain-Old Ruby Object (PORO) # How to serialize a Plain-Old Ruby Object (PORO)
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: 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 in most situations:
```ruby ```ruby
# my_model.rb # my_model.rb
class MyModel class MyModel
alias :read_attribute_for_serialization :send alias :read_attribute_for_serialization :send
attr_accessor :id, :name, :level attr_accessor :id, :name, :level
def initialize(attributes) def initialize(attributes)
@id = attributes[:id] @id = attributes[:id]
@name = attributes[:name] @name = attributes[:name]
@ -21,12 +24,22 @@ class MyModel
end end
``` ```
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: The [ActiveModel::Serializer::Lint::Tests](../../lib/active_model/serializer/lint.rb)
define and validate which methods ActiveModelSerializers expects to be implemented.
An implementation of the complete spec is included either for use or as reference:
[`ActiveModelSerializers::Model`](../../lib/active_model_serializers/model.rb).
You can use in production code that will make your PORO a lot cleaner.
The above code now becomes:
```ruby ```ruby
# my_model.rb # my_model.rb
class MyModel < ActiveModelSerializers::Model class MyModel < ActiveModelSerializers::Model
attr_accessor :id, :name, :level attributes :id, :name, :level
end end
``` ```
The default serializer would be `MyModelSerializer`. The default serializer would be `MyModelSerializer`.
For more information, see [README: What does a 'serializable resource' look like?](../../README.md#what-does-a-serializable-resource-look-like).

View File

@ -38,6 +38,14 @@ module ActiveModelSerializers
@default_include_directive ||= JSONAPI::IncludeDirective.new(config.default_includes, allow_wildcard: true) @default_include_directive ||= JSONAPI::IncludeDirective.new(config.default_includes, allow_wildcard: true)
end end
def self.silence_warnings
original_verbose = $VERBOSE
$VERBOSE = nil
yield
ensure
$VERBOSE = original_verbose
end
require 'active_model/serializer/version' require 'active_model/serializer/version'
require 'active_model/serializer' require 'active_model/serializer'
require 'active_model/serializable_resource' require 'active_model/serializable_resource'

View File

@ -1,42 +1,94 @@
# ActiveModelSerializers::Model is a convenient # ActiveModelSerializers::Model is a convenient superclass for making your models
# serializable class to inherit from when making # from Plain-Old Ruby Objects (PORO). It also serves as a reference implementation
# serializable non-activerecord objects. # that satisfies ActiveModel::Serializer::Lint::Tests.
module ActiveModelSerializers module ActiveModelSerializers
class Model class Model
include ActiveModel::Model
include ActiveModel::Serializers::JSON include ActiveModel::Serializers::JSON
include ActiveModel::Model
attr_reader :attributes, :errors # Easily declare instance attributes with setters and getters for each.
#
# All attributes to initialize an instance must have setters.
# However, the hash turned by +attributes+ instance method will ALWAYS
# be the value of the initial attributes, regardless of what accessors are defined.
# The only way to change the change the attributes after initialization is
# to mutate the +attributes+ directly.
# Accessor methods do NOT mutate the attributes. (This is a bug).
#
# @note For now, the Model only supports the notion of 'attributes'.
# In the tests, there is a special Model that also supports 'associations'. This is
# important so that we can add accessors for values that should not appear in the
# attributes hash when modeling associations. It is not yet clear if it
# makes sense for a PORO to have associations outside of the tests.
#
# @overload attributes(names)
# @param names [Array<String, Symbol>]
# @param name [String, Symbol]
def self.attributes(*names)
# Silence redefinition of methods warnings
ActiveModelSerializers.silence_warnings do
attr_accessor(*names)
end
end
# Support for validation and other ActiveModel::Errors
# @return [ActiveModel::Errors]
attr_reader :errors
# (see #updated_at)
attr_writer :updated_at
# The only way to change the attributes of an instance is to directly mutate the attributes.
# @example
#
# model.attributes[:foo] = :bar
# @return [Hash]
attr_reader :attributes
# @param attributes [Hash]
def initialize(attributes = {}) def initialize(attributes = {})
@attributes = attributes && attributes.symbolize_keys attributes ||= {} # protect against nil
@attributes = attributes.symbolize_keys.with_indifferent_access
@errors = ActiveModel::Errors.new(self) @errors = ActiveModel::Errors.new(self)
super super
end end
# Defaults to the downcased model name. # Defaults to the downcased model name.
# This probably isn't a good default, since it's not a unique instance identifier,
# but that's what is currently implemented \_('-')_/.
#
# @note Though +id+ is defined, it will only show up
# in +attributes+ when it is passed in to the initializer or added to +attributes+,
# such as <tt>attributes[:id] = 5</tt>.
# @return [String, Numeric, Symbol]
def id def id
attributes.fetch(:id) { self.class.name.downcase } attributes.fetch(:id) do
end defined?(@id) ? @id : self.class.model_name.name && self.class.model_name.name.downcase
# Defaults to the downcased model name and updated_at
def cache_key
attributes.fetch(:cache_key) { "#{self.class.name.downcase}/#{id}-#{updated_at.strftime('%Y%m%d%H%M%S%9N')}" }
end
# Defaults to the time the serializer file was modified.
def updated_at
attributes.fetch(:updated_at) { File.mtime(__FILE__) }
end
def read_attribute_for_serialization(key)
if key == :id || key == 'id'
attributes.fetch(key) { id }
else
attributes[key]
end end
end end
# When not set, defaults to the time the file was modified.
#
# @note Though +updated_at+ and +updated_at=+ are defined, it will only show up
# in +attributes+ when it is passed in to the initializer or added to +attributes+,
# such as <tt>attributes[:updated_at] = Time.current</tt>.
# @return [String, Numeric, Time]
def updated_at
attributes.fetch(:updated_at) do
defined?(@updated_at) ? @updated_at : File.mtime(__FILE__)
end
end
# To customize model behavior, this method must be redefined. However,
# there are other ways of setting the +cache_key+ a serializer uses.
# @return [String]
def cache_key
ActiveSupport::Cache.expand_cache_key([
self.class.model_name.name.downcase,
"#{id}-#{updated_at.strftime('%Y%m%d%H%M%S%9N')}"
].compact)
end
# The following methods are needed to be minimally implemented for ActiveModel::Errors # The following methods are needed to be minimally implemented for ActiveModel::Errors
# :nocov: # :nocov:
def self.human_attribute_name(attr, _options = {}) def self.human_attribute_name(attr, _options = {})

View File

@ -15,7 +15,7 @@ module ActionController
end end
def render_skipping_adapter def render_skipping_adapter
@profile = Profile.new(name: 'Name 1', description: 'Description 1', comments: 'Comments 1') @profile = Profile.new(id: 'render_skipping_adapter_id', name: 'Name 1', description: 'Description 1', comments: 'Comments 1')
render json: @profile, adapter: false render json: @profile, adapter: false
end end
end end
@ -46,7 +46,7 @@ module ActionController
def test_render_skipping_adapter def test_render_skipping_adapter
get :render_skipping_adapter get :render_skipping_adapter
assert_equal '{"name":"Name 1","description":"Description 1","comments":"Comments 1"}', response.body assert_equal '{"id":"render_skipping_adapter_id","name":"Name 1","description":"Description 1"}', response.body
end end
end end
end end

View File

@ -5,7 +5,16 @@ module ActionController
class JsonApi class JsonApi
class FieldsTest < ActionController::TestCase class FieldsTest < ActionController::TestCase
class FieldsTestController < ActionController::Base class FieldsTestController < ActionController::Base
class PostSerializer < ActiveModel::Serializer class AuthorWithName < Author
attributes :first_name, :last_name
end
class AuthorWithNameSerializer < AuthorSerializer
type 'authors'
end
class PostWithPublishAt < Post
attributes :publish_at
end
class PostWithPublishAtSerializer < ActiveModel::Serializer
type 'posts' type 'posts'
attributes :title, :body, :publish_at attributes :title, :body, :publish_at
belongs_to :author belongs_to :author
@ -14,19 +23,19 @@ module ActionController
def setup_post def setup_post
ActionController::Base.cache_store.clear ActionController::Base.cache_store.clear
@author = Author.new(id: 1, first_name: 'Bob', last_name: 'Jones') @author = AuthorWithName.new(id: 1, first_name: 'Bob', last_name: 'Jones')
@comment1 = Comment.new(id: 7, body: 'cool', author: @author) @comment1 = Comment.new(id: 7, body: 'cool', author: @author)
@comment2 = Comment.new(id: 12, body: 'awesome', author: @author) @comment2 = Comment.new(id: 12, body: 'awesome', author: @author)
@post = Post.new(id: 1337, title: 'Title 1', body: 'Body 1', @post = PostWithPublishAt.new(id: 1337, title: 'Title 1', body: 'Body 1',
author: @author, comments: [@comment1, @comment2], author: @author, comments: [@comment1, @comment2],
publish_at: '2020-03-16T03:55:25.291Z') publish_at: '2020-03-16T03:55:25.291Z')
@comment1.post = @post @comment1.post = @post
@comment2.post = @post @comment2.post = @post
end end
def render_fields_works_on_relationships def render_fields_works_on_relationships
setup_post setup_post
render json: @post, serializer: PostSerializer, adapter: :json_api, fields: { posts: [:author] } render json: @post, serializer: PostWithPublishAtSerializer, adapter: :json_api, fields: { posts: [:author] }
end end
end end

View File

@ -5,9 +5,17 @@ module ActionController
class JsonApi class JsonApi
class KeyTransformTest < ActionController::TestCase class KeyTransformTest < ActionController::TestCase
class KeyTransformTestController < ActionController::Base class KeyTransformTestController < ActionController::Base
class Post < ::Model; end class Post < ::Model
class Author < ::Model; end attributes :title, :body, :publish_at
class TopComment < ::Model; end associations :author, :top_comments
end
class Author < ::Model
attributes :first_name, :last_name
end
class TopComment < ::Model
attributes :body
associations :author, :post
end
class PostSerializer < ActiveModel::Serializer class PostSerializer < ActiveModel::Serializer
type 'posts' type 'posts'
attributes :title, :body, :publish_at attributes :title, :body, :publish_at

View File

@ -3,10 +3,16 @@ require 'test_helper'
module ActionController module ActionController
module Serialization module Serialization
class NamespaceLookupTest < ActionController::TestCase class NamespaceLookupTest < ActionController::TestCase
class Book < ::Model; end class Book < ::Model
class Page < ::Model; end attributes :title, :body
class Chapter < ::Model; end associations :writer, :chapters
class Writer < ::Model; end end
class Chapter < ::Model
attributes :title
end
class Writer < ::Model
attributes :name
end
module Api module Api
module V2 module V2
@ -93,7 +99,7 @@ module ActionController
end end
def invalid_namespace def invalid_namespace
book = Book.new(title: 'New Post', body: 'Body') book = Book.new(id: 'invalid_namespace_book_id', title: 'New Post', body: 'Body')
render json: book, namespace: :api_v2 render json: book, namespace: :api_v2
end end
@ -205,7 +211,7 @@ module ActionController
assert_serializer ActiveModel::Serializer::Null assert_serializer ActiveModel::Serializer::Null
expected = { 'title' => 'New Post', 'body' => 'Body' } expected = { 'id' => 'invalid_namespace_book_id', 'title' => 'New Post', 'body' => 'Body' }
actual = JSON.parse(@response.body) actual = JSON.parse(@response.body)
assert_equal expected, actual assert_equal expected, actual

View File

@ -2,16 +2,16 @@ require 'test_helper'
module SerializationScopeTesting module SerializationScopeTesting
class User < ActiveModelSerializers::Model class User < ActiveModelSerializers::Model
attr_accessor :id, :name, :admin attributes :id, :name, :admin
def admin? def admin?
admin admin
end end
end end
class Comment < ActiveModelSerializers::Model class Comment < ActiveModelSerializers::Model
attr_accessor :id, :body attributes :id, :body
end end
class Post < ActiveModelSerializers::Model class Post < ActiveModelSerializers::Model
attr_accessor :id, :title, :body, :comments attributes :id, :title, :body, :comments
end end
class PostSerializer < ActiveModel::Serializer class PostSerializer < ActiveModel::Serializer
attributes :id, :title, :body, :comments attributes :id, :title, :body, :comments

View File

@ -135,7 +135,7 @@ module ActionController
like = Like.new(id: 1, likeable: comment, time: 3.days.ago) like = Like.new(id: 1, likeable: comment, time: 3.days.ago)
generate_cached_serializer(like) generate_cached_serializer(like)
like.likable = comment2 like.likeable = comment2
like.time = Time.zone.now.to_s like.time = Time.zone.now.to_s
render json: like render json: like

View File

@ -4,13 +4,13 @@ module ActiveModelSerializers
class ModelTest < ActiveSupport::TestCase class ModelTest < ActiveSupport::TestCase
include ActiveModel::Serializer::Lint::Tests include ActiveModel::Serializer::Lint::Tests
def setup setup do
@resource = ActiveModelSerializers::Model.new @resource = ActiveModelSerializers::Model.new
end end
def test_initialization_with_string_keys def test_initialization_with_string_keys
klass = Class.new(ActiveModelSerializers::Model) do klass = Class.new(ActiveModelSerializers::Model) do
attr_accessor :key attributes :key
end end
value = 'value' value = 'value'
@ -18,5 +18,68 @@ module ActiveModelSerializers
assert_equal model_instance.read_attribute_for_serialization(:key), value assert_equal model_instance.read_attribute_for_serialization(:key), value
end end
def test_attributes_can_be_read_for_serialization
klass = Class.new(ActiveModelSerializers::Model) do
attributes :one, :two, :three
end
original_attributes = { one: 1, two: 2, three: 3 }
original_instance = klass.new(original_attributes)
# Initial value
instance = original_instance
expected_attributes = { one: 1, two: 2, three: 3 }.with_indifferent_access
assert_equal expected_attributes, instance.attributes
assert_equal 1, instance.one
assert_equal 1, instance.read_attribute_for_serialization(:one)
# FIXME: Change via accessor has no effect on attributes.
instance = original_instance.dup
instance.one = :not_one
assert_equal expected_attributes, instance.attributes
assert_equal :not_one, instance.one
assert_equal :not_one, instance.read_attribute_for_serialization(:one)
# FIXME: Change via mutating attributes
instance = original_instance.dup
instance.attributes[:one] = :not_one
expected_attributes = { one: :not_one, two: 2, three: 3 }.with_indifferent_access
assert_equal expected_attributes, instance.attributes
assert_equal 1, instance.one
assert_equal 1, instance.read_attribute_for_serialization(:one)
end
def test_id_attribute_can_be_read_for_serialization
klass = Class.new(ActiveModelSerializers::Model) do
attributes :id, :one, :two, :three
end
self.class.const_set(:SomeTestModel, klass)
original_attributes = { id: :ego, one: 1, two: 2, three: 3 }
original_instance = klass.new(original_attributes)
# Initial value
instance = original_instance.dup
expected_attributes = { id: :ego, one: 1, two: 2, three: 3 }.with_indifferent_access
assert_equal expected_attributes, instance.attributes
assert_equal :ego, instance.id
assert_equal :ego, instance.read_attribute_for_serialization(:id)
# FIXME: Change via accessor has no effect on attributes.
instance = original_instance.dup
instance.id = :superego
assert_equal expected_attributes, instance.attributes
assert_equal :superego, instance.id
assert_equal :superego, instance.read_attribute_for_serialization(:id)
# FIXME: Change via mutating attributes
instance = original_instance.dup
instance.attributes[:id] = :superego
expected_attributes = { id: :superego, one: 1, two: 2, three: 3 }.with_indifferent_access
assert_equal expected_attributes, instance.attributes
assert_equal :ego, instance.id
assert_equal :ego, instance.read_attribute_for_serialization(:id)
ensure
self.class.send(:remove_const, :SomeTestModel)
end
end end
end end

View File

@ -44,7 +44,7 @@ class JsonApiRendererTest < ActionDispatch::IntegrationTest
def define_author_model_and_serializer def define_author_model_and_serializer
TestController.const_set(:Author, Class.new(ActiveModelSerializers::Model) do TestController.const_set(:Author, Class.new(ActiveModelSerializers::Model) do
attr_accessor :id, :name attributes :id, :name
end) end)
TestController.const_set(:AuthorSerializer, Class.new(ActiveModel::Serializer) do TestController.const_set(:AuthorSerializer, Class.new(ActiveModel::Serializer) do
type 'users' type 'users'

View File

@ -3,11 +3,8 @@ require 'test_helper'
module ActiveModelSerializers module ActiveModelSerializers
module Adapter module Adapter
class AttributesTest < ActiveSupport::TestCase class AttributesTest < ActiveSupport::TestCase
class Person class Person < ActiveModelSerializers::Model
include ActiveModel::Model attributes :first_name, :last_name
include ActiveModel::Serialization
attr_accessor :first_name, :last_name
end end
class PersonSerializer < ActiveModel::Serializer class PersonSerializer < ActiveModel::Serializer

View File

@ -4,9 +4,17 @@ module ActiveModelSerializers
module Adapter module Adapter
class JsonApi class JsonApi
class FieldsTest < ActiveSupport::TestCase class FieldsTest < ActiveSupport::TestCase
class Post < ::Model; end class Post < ::Model
class Author < ::Model; end attributes :title, :body
class Comment < ::Model; end associations :author, :comments
end
class Author < ::Model
attributes :name, :birthday
end
class Comment < ::Model
attributes :body
associations :author, :post
end
class PostSerializer < ActiveModel::Serializer class PostSerializer < ActiveModel::Serializer
type 'posts' type 'posts'

View File

@ -5,7 +5,9 @@ module ActiveModel
module Adapter module Adapter
class JsonApi class JsonApi
class IncludeParamTest < ActiveSupport::TestCase class IncludeParamTest < ActiveSupport::TestCase
IncludeParamAuthor = Class.new(::Model) IncludeParamAuthor = Class.new(::Model) do
associations :tags, :posts
end
class CustomCommentLoader class CustomCommentLoader
def all def all

View File

@ -1,6 +1,6 @@
require 'test_helper' require 'test_helper'
class NestedPost < ::Model; end class NestedPost < ::Model; associations :nested_posts end
class NestedPostSerializer < ActiveModel::Serializer class NestedPostSerializer < ActiveModel::Serializer
has_many :nested_posts has_many :nested_posts
end end
@ -301,8 +301,8 @@ module ActiveModelSerializers
end end
class NoDuplicatesTest < ActiveSupport::TestCase class NoDuplicatesTest < ActiveSupport::TestCase
class Post < ::Model; end class Post < ::Model; associations :author end
class Author < ::Model; end class Author < ::Model; associations :posts, :roles, :bio end
class PostSerializer < ActiveModel::Serializer class PostSerializer < ActiveModel::Serializer
type 'posts' type 'posts'

View File

@ -4,7 +4,7 @@ module ActiveModelSerializers
module Adapter module Adapter
class JsonApi class JsonApi
class LinksTest < ActiveSupport::TestCase class LinksTest < ActiveSupport::TestCase
class LinkAuthor < ::Model; end class LinkAuthor < ::Model; associations :posts end
class LinkAuthorSerializer < ActiveModel::Serializer class LinkAuthorSerializer < ActiveModel::Serializer
link :self do link :self do
href "http://example.com/link_author/#{object.id}" href "http://example.com/link_author/#{object.id}"

View File

@ -384,7 +384,7 @@ module ActiveModelSerializers
def new_model(model_attributes) def new_model(model_attributes)
Class.new(ActiveModelSerializers::Model) do Class.new(ActiveModelSerializers::Model) do
attr_accessor(*model_attributes.keys) attributes(*model_attributes.keys)
def self.name def self.name
'TestModel' 'TestModel'

View File

@ -4,9 +4,17 @@ module ActiveModelSerializers
module Adapter module Adapter
class JsonApi class JsonApi
class KeyCaseTest < ActiveSupport::TestCase class KeyCaseTest < ActiveSupport::TestCase
class Post < ::Model; end class Post < ::Model
class Author < ::Model; end attributes :title, :body, :publish_at
class Comment < ::Model; end associations :author, :comments
end
class Author < ::Model
attributes :first_name, :last_name
end
class Comment < ::Model
attributes :body
associations :author, :post
end
class PostSerializer < ActiveModel::Serializer class PostSerializer < ActiveModel::Serializer
type 'posts' type 'posts'

View File

@ -34,6 +34,7 @@ module ActiveModelSerializers
end end
class Article < ::Model class Article < ::Model
attributes :title
# To confirm error is raised when cache_key is not set and cache_key option not passed to cache # To confirm error is raised when cache_key is not set and cache_key option not passed to cache
undef_method :cache_key undef_method :cache_key
end end
@ -48,6 +49,16 @@ module ActiveModelSerializers
attribute :special_attribute attribute :special_attribute
end end
class Comment < ::Model
attributes :body
associations :post, :author
# Uses a custom non-time-based cache key
def cache_key
"comment/#{id}"
end
end
setup do setup do
cache_store.clear cache_store.clear
@comment = Comment.new(id: 1, body: 'ZOMG A COMMENT') @comment = Comment.new(id: 1, body: 'ZOMG A COMMENT')
@ -244,7 +255,7 @@ module ActiveModelSerializers
# rubocop:disable Metrics/AbcSize # rubocop:disable Metrics/AbcSize
def test_a_serializer_rendered_by_two_adapter_returns_differently_fetch_attributes def test_a_serializer_rendered_by_two_adapter_returns_differently_fetch_attributes
Object.const_set(:Alert, Class.new(ActiveModelSerializers::Model) do Object.const_set(:Alert, Class.new(ActiveModelSerializers::Model) do
attr_accessor :id, :status, :resource, :started_at, :ended_at, :updated_at, :created_at attributes :id, :status, :resource, :started_at, :ended_at, :updated_at, :created_at
end) end)
Object.const_set(:UncachedAlertSerializer, Class.new(ActiveModel::Serializer) do Object.const_set(:UncachedAlertSerializer, Class.new(ActiveModel::Serializer) do
attributes :id, :status, :resource, :started_at, :ended_at, :updated_at, :created_at attributes :id, :status, :resource, :started_at, :ended_at, :updated_at, :created_at
@ -271,7 +282,7 @@ module ActiveModelSerializers
ended_at: nil, ended_at: nil,
updated_at: alert.updated_at, updated_at: alert.updated_at,
created_at: alert.created_at created_at: alert.created_at
} }.with_indifferent_access
expected_cached_jsonapi_attributes = { expected_cached_jsonapi_attributes = {
id: '1', id: '1',
type: 'alerts', type: 'alerts',
@ -283,15 +294,15 @@ module ActiveModelSerializers
updated_at: alert.updated_at, updated_at: alert.updated_at,
created_at: alert.created_at created_at: alert.created_at
} }
} }.with_indifferent_access
# Assert attributes are serialized correctly # Assert attributes are serialized correctly
serializable_alert = serializable(alert, serializer: AlertSerializer, adapter: :attributes) serializable_alert = serializable(alert, serializer: AlertSerializer, adapter: :attributes)
attributes_serialization = serializable_alert.as_json attributes_serialization = serializable_alert.as_json.with_indifferent_access
assert_equal expected_fetch_attributes, alert.attributes assert_equal expected_fetch_attributes, alert.attributes
assert_equal alert.attributes, attributes_serialization assert_equal alert.attributes, attributes_serialization
attributes_cache_key = serializable_alert.adapter.serializer.cache_key(serializable_alert.adapter) attributes_cache_key = serializable_alert.adapter.serializer.cache_key(serializable_alert.adapter)
assert_equal attributes_serialization, cache_store.fetch(attributes_cache_key) assert_equal attributes_serialization, cache_store.fetch(attributes_cache_key).with_indifferent_access
serializable_alert = serializable(alert, serializer: AlertSerializer, adapter: :json_api) serializable_alert = serializable(alert, serializer: AlertSerializer, adapter: :json_api)
jsonapi_cache_key = serializable_alert.adapter.serializer.cache_key(serializable_alert.adapter) jsonapi_cache_key = serializable_alert.adapter.serializer.cache_key(serializable_alert.adapter)
@ -303,7 +314,7 @@ module ActiveModelSerializers
serializable_alert = serializable(alert, serializer: UncachedAlertSerializer, adapter: :json_api) serializable_alert = serializable(alert, serializer: UncachedAlertSerializer, adapter: :json_api)
assert_equal serializable_alert.as_json, jsonapi_serialization assert_equal serializable_alert.as_json, jsonapi_serialization
cached_serialization = cache_store.fetch(jsonapi_cache_key) cached_serialization = cache_store.fetch(jsonapi_cache_key).with_indifferent_access
assert_equal expected_cached_jsonapi_attributes, cached_serialization assert_equal expected_cached_jsonapi_attributes, cached_serialization
ensure ensure
Object.send(:remove_const, :Alert) Object.send(:remove_const, :Alert)
@ -329,11 +340,15 @@ module ActiveModelSerializers
actual = ActiveModel::Serializer.object_cache_keys(serializable.adapter.serializer, serializable.adapter, include_directive) actual = ActiveModel::Serializer.object_cache_keys(serializable.adapter.serializer, serializable.adapter, include_directive)
assert_equal 3, actual.size assert_equal 3, actual.size
assert actual.any? { |key| key == "comment/1/#{serializable.adapter.cache_key}" } expected_key = "comment/1/#{serializable.adapter.cache_key}"
assert actual.any? { |key| key =~ %r{post/post-\d+} } assert actual.any? { |key| key == expected_key }, "actual '#{actual}' should include #{expected_key}"
assert actual.any? { |key| key =~ %r{author/author-\d+} } expected_key = %r{post/post-\d+}
assert actual.any? { |key| key =~ expected_key }, "actual '#{actual}' should match '#{expected_key}'"
expected_key = %r{author/author-\d+}
assert actual.any? { |key| key =~ expected_key }, "actual '#{actual}' should match '#{expected_key}'"
end end
# rubocop:disable Metrics/AbcSize
def test_fetch_attributes_from_cache def test_fetch_attributes_from_cache
serializers = ActiveModel::Serializer::CollectionSerializer.new([@comment, @comment]) serializers = ActiveModel::Serializer::CollectionSerializer.new([@comment, @comment])
@ -344,10 +359,10 @@ module ActiveModelSerializers
adapter_options = {} adapter_options = {}
adapter_instance = ActiveModelSerializers::Adapter::Attributes.new(serializers, adapter_options) adapter_instance = ActiveModelSerializers::Adapter::Attributes.new(serializers, adapter_options)
serializers.serializable_hash(adapter_options, options, adapter_instance) serializers.serializable_hash(adapter_options, options, adapter_instance)
cached_attributes = adapter_options.fetch(:cached_attributes) cached_attributes = adapter_options.fetch(:cached_attributes).with_indifferent_access
include_directive = ActiveModelSerializers.default_include_directive include_directive = ActiveModelSerializers.default_include_directive
manual_cached_attributes = ActiveModel::Serializer.cache_read_multi(serializers, adapter_instance, include_directive) manual_cached_attributes = ActiveModel::Serializer.cache_read_multi(serializers, adapter_instance, include_directive).with_indifferent_access
assert_equal manual_cached_attributes, cached_attributes assert_equal manual_cached_attributes, cached_attributes
assert_equal cached_attributes["#{@comment.cache_key}/#{adapter_instance.cache_key}"], Comment.new(id: 1, body: 'ZOMG A COMMENT').attributes assert_equal cached_attributes["#{@comment.cache_key}/#{adapter_instance.cache_key}"], Comment.new(id: 1, body: 'ZOMG A COMMENT').attributes
@ -358,6 +373,7 @@ module ActiveModelSerializers
assert_equal cached_attributes["#{writer_cache_key}/#{adapter_instance.cache_key}"], Author.new(id: 'author', name: 'Joao M. D. Moura').attributes assert_equal cached_attributes["#{writer_cache_key}/#{adapter_instance.cache_key}"], Author.new(id: 'author', name: 'Joao M. D. Moura').attributes
end end
end end
# rubocop:enable Metrics/AbcSize
def test_cache_read_multi_with_fragment_cache_enabled def test_cache_read_multi_with_fragment_cache_enabled
post_serializer = Class.new(ActiveModel::Serializer) do post_serializer = Class.new(ActiveModel::Serializer) do

View File

@ -3,14 +3,27 @@ require 'test_helper'
module ActiveModel module ActiveModel
class Serializer class Serializer
class CollectionSerializerTest < ActiveSupport::TestCase class CollectionSerializerTest < ActiveSupport::TestCase
class SingularModel < ::Model; end
class SingularModelSerializer < ActiveModel::Serializer
end
class HasManyModel < ::Model
associations :singular_models
end
class HasManyModelSerializer < ActiveModel::Serializer
has_many :singular_models
def custom_options
instance_options
end
end
class MessagesSerializer < ActiveModel::Serializer class MessagesSerializer < ActiveModel::Serializer
type 'messages' type 'messages'
end end
def setup def setup
@comment = Comment.new @singular_model = SingularModel.new
@post = Post.new @has_many_model = HasManyModel.new
@resource = build_named_collection @comment, @post @resource = build_named_collection @singular_model, @has_many_model
@serializer = collection_serializer.new(@resource, some: :options) @serializer = collection_serializer.new(@resource, some: :options)
end end
@ -34,29 +47,29 @@ module ActiveModel
def test_each_object_should_be_serialized_with_appropriate_serializer def test_each_object_should_be_serialized_with_appropriate_serializer
serializers = @serializer.to_a serializers = @serializer.to_a
assert_kind_of CommentSerializer, serializers.first assert_kind_of SingularModelSerializer, serializers.first
assert_kind_of Comment, serializers.first.object assert_kind_of SingularModel, serializers.first.object
assert_kind_of PostSerializer, serializers.last assert_kind_of HasManyModelSerializer, serializers.last
assert_kind_of Post, serializers.last.object assert_kind_of HasManyModel, serializers.last.object
assert_equal :options, serializers.last.custom_options[:some] assert_equal :options, serializers.last.custom_options[:some]
end end
def test_serializer_option_not_passed_to_each_serializer def test_serializer_option_not_passed_to_each_serializer
serializers = collection_serializer.new([@post], serializer: PostSerializer).to_a serializers = collection_serializer.new([@has_many_model], serializer: HasManyModelSerializer).to_a
refute serializers.first.custom_options.key?(:serializer) refute serializers.first.custom_options.key?(:serializer)
end end
def test_root_default def test_root_default
@serializer = collection_serializer.new([@comment, @post]) @serializer = collection_serializer.new([@singular_model, @has_many_model])
assert_nil @serializer.root assert_nil @serializer.root
end end
def test_root def test_root
expected = 'custom_root' expected = 'custom_root'
@serializer = collection_serializer.new([@comment, @post], root: expected) @serializer = collection_serializer.new([@singular_model, @has_many_model], root: expected)
assert_equal expected, @serializer.root assert_equal expected, @serializer.root
end end

View File

@ -47,16 +47,6 @@ module ARModels
has_many :comments has_many :comments
belongs_to :author belongs_to :author
end end
class Comment < ActiveRecord::Base
belongs_to :post
belongs_to :author
end
class Author < ActiveRecord::Base
has_many :posts
end
class PostSerializer < ActiveModel::Serializer class PostSerializer < ActiveModel::Serializer
attributes :id, :title, :body attributes :id, :title, :body
@ -64,15 +54,60 @@ module ARModels
belongs_to :author belongs_to :author
end end
class Comment < ActiveRecord::Base
belongs_to :post
belongs_to :author
end
class CommentSerializer < ActiveModel::Serializer class CommentSerializer < ActiveModel::Serializer
attributes :id, :contents attributes :id, :contents
belongs_to :author belongs_to :author
end end
class Author < ActiveRecord::Base
has_many :posts
end
class AuthorSerializer < ActiveModel::Serializer class AuthorSerializer < ActiveModel::Serializer
attributes :id, :name attributes :id, :name
has_many :posts has_many :posts
end end
end end
class Employee < ActiveRecord::Base
has_many :pictures, as: :imageable
has_many :object_tags, as: :taggable
end
class PolymorphicSimpleSerializer < ActiveModel::Serializer
attributes :id
end
class ObjectTag < ActiveRecord::Base
belongs_to :poly_tag
belongs_to :taggable, polymorphic: true
end
class PolymorphicObjectTagSerializer < ActiveModel::Serializer
attributes :id
has_many :taggable, serializer: PolymorphicSimpleSerializer, polymorphic: true
end
class PolyTag < ActiveRecord::Base
has_many :object_tags
end
class PolymorphicTagSerializer < ActiveModel::Serializer
attributes :id, :phrase
has_many :object_tags, serializer: PolymorphicObjectTagSerializer
end
class Picture < ActiveRecord::Base
belongs_to :imageable, polymorphic: true
has_many :object_tags, as: :taggable
end
class PolymorphicHasManySerializer < ActiveModel::Serializer
attributes :id, :name
end
class PolymorphicBelongsToSerializer < ActiveModel::Serializer
attributes :id, :title
has_one :imageable, serializer: PolymorphicHasManySerializer, polymorphic: true
end

309
test/fixtures/poro.rb vendored
View File

@ -1,25 +1,28 @@
verbose = $VERBOSE
$VERBOSE = nil
class Model < ActiveModelSerializers::Model class Model < ActiveModelSerializers::Model
FILE_DIGEST = Digest::MD5.hexdigest(File.open(__FILE__).read) FILE_DIGEST = Digest::MD5.hexdigest(File.open(__FILE__).read)
### Helper methods, not required to be serializable attr_writer :id
# Convenience when not adding @attributes readers and writers # At this time, just for organization of intent
def method_missing(meth, *args) class_attribute :association_names
if meth.to_s =~ /^(.*)=$/ self.association_names = []
attributes[Regexp.last_match(1).to_sym] = args[0]
elsif attributes.key?(meth) def self.associations(*names)
attributes[meth] self.association_names |= names.map(&:to_sym)
else # Silence redefinition of methods warnings
super ActiveModelSerializers.silence_warnings do
attr_accessor(*names)
end end
end end
# required for ActiveModel::AttributeAssignment#_assign_attribute def associations
# in Rails 5 association_names.each_with_object({}) do |association_name, result|
def respond_to_missing?(method_name, _include_private = false) result[association_name] = public_send(association_name).freeze
attributes.key?(method_name.to_s.tr('=', '').to_sym) || super end.with_indifferent_access.freeze
end
def attributes
super.except(*association_names)
end end
end end
@ -30,67 +33,59 @@ end
# model = ModelWithErrors.new # model = ModelWithErrors.new
# model.validate! # => ["cannot be nil"] # model.validate! # => ["cannot be nil"]
# model.errors.full_messages # => ["name cannot be nil"] # model.errors.full_messages # => ["name cannot be nil"]
class ModelWithErrors < ::ActiveModelSerializers::Model class ModelWithErrors < Model
attr_accessor :name attributes :name
end end
class Profile < Model class Profile < Model
attributes :name, :description
associations :comments
end end
class ProfileSerializer < ActiveModel::Serializer class ProfileSerializer < ActiveModel::Serializer
attributes :name, :description attributes :name, :description
# TODO: is this used anywhere?
def arguments_passed_in?
instance_options[:my_options] == :accessible
end
end end
class ProfilePreviewSerializer < ActiveModel::Serializer class ProfilePreviewSerializer < ActiveModel::Serializer
attributes :name attributes :name
end end
class Post < Model; end class Author < Model
class Like < Model; end attributes :name
class Author < Model; end associations :posts, :bio, :roles, :comments
class Bio < Model; end end
class Blog < Model; end class AuthorSerializer < ActiveModel::Serializer
class Role < Model; end cache key: 'writer', skip_digest: true
class User < Model; end attribute :id
class Location < Model; end attribute :name
class Place < Model; end
class Tag < Model; end has_many :posts
class VirtualValue < Model; end has_many :roles
has_one :bio
end
class AuthorPreviewSerializer < ActiveModel::Serializer
attributes :id
has_many :posts
end
class Comment < Model class Comment < Model
# Uses a custom non-time-based cache key attributes :body, :date
def cache_key associations :post, :author, :likes
"#{self.class.name.downcase}/#{id}" end
end class CommentSerializer < ActiveModel::Serializer
cache expires_in: 1.day, skip_digest: true
attributes :id, :body
belongs_to :post
belongs_to :author
end
class CommentPreviewSerializer < ActiveModel::Serializer
attributes :id
belongs_to :post
end end
class Employee < ActiveRecord::Base class Post < Model
has_many :pictures, as: :imageable attributes :title, :body
has_many :object_tags, as: :taggable associations :author, :comments, :blog, :tags, :related
end end
class ObjectTag < ActiveRecord::Base
belongs_to :poly_tag
belongs_to :taggable, polymorphic: true
end
class Picture < ActiveRecord::Base
belongs_to :imageable, polymorphic: true
has_many :object_tags, as: :taggable
end
class PolyTag < ActiveRecord::Base
has_many :object_tags
end
module Spam
class UnrelatedLink < Model; end
end
class PostSerializer < ActiveModel::Serializer class PostSerializer < ActiveModel::Serializer
cache key: 'post', expires_in: 0.1, skip_digest: true cache key: 'post', expires_in: 0.1, skip_digest: true
attributes :id, :title, :body attributes :id, :title, :body
@ -102,58 +97,79 @@ class PostSerializer < ActiveModel::Serializer
def blog def blog
Blog.new(id: 999, name: 'Custom blog') Blog.new(id: 999, name: 'Custom blog')
end end
# TODO: is this used anywhere?
def custom_options
instance_options
end
end end
class SpammyPostSerializer < ActiveModel::Serializer class SpammyPostSerializer < ActiveModel::Serializer
attributes :id attributes :id
has_many :related has_many :related
end end
class PostPreviewSerializer < ActiveModel::Serializer
attributes :title, :body, :id
class CommentSerializer < ActiveModel::Serializer has_many :comments, serializer: ::CommentPreviewSerializer
cache expires_in: 1.day, skip_digest: true belongs_to :author, serializer: ::AuthorPreviewSerializer
attributes :id, :body end
class PostWithTagsSerializer < ActiveModel::Serializer
attributes :id
has_many :tags
end
class PostWithCustomKeysSerializer < ActiveModel::Serializer
attributes :id
has_many :comments, key: :reviews
belongs_to :author, key: :writer
has_one :blog, key: :site
end
class Bio < Model
attributes :content, :rating
associations :author
end
class BioSerializer < ActiveModel::Serializer
cache except: [:content], skip_digest: true
attributes :id, :content, :rating
belongs_to :post
belongs_to :author belongs_to :author
def custom_options
instance_options
end
end end
class AuthorSerializer < ActiveModel::Serializer class Blog < Model
cache key: 'writer', skip_digest: true attributes :name, :type, :special_attribute
associations :writer, :articles
end
class BlogSerializer < ActiveModel::Serializer
cache key: 'blog'
attributes :id, :name
belongs_to :writer
has_many :articles
end
class AlternateBlogSerializer < ActiveModel::Serializer
attribute :id attribute :id
attribute :name attribute :name, key: :title
end
has_many :posts class CustomBlogSerializer < ActiveModel::Serializer
has_many :roles attribute :id
has_one :bio attribute :special_attribute
has_many :articles
end end
class Role < Model
attributes :name, :description, :special_attribute
associations :author
end
class RoleSerializer < ActiveModel::Serializer class RoleSerializer < ActiveModel::Serializer
cache only: [:name, :slug], skip_digest: true cache only: [:name, :slug], skip_digest: true
attributes :id, :name, :description attributes :id, :name, :description
attribute :friendly_id, key: :slug attribute :friendly_id, key: :slug
belongs_to :author
def friendly_id def friendly_id
"#{object.name}-#{object.id}" "#{object.name}-#{object.id}"
end end
belongs_to :author
end end
class LikeSerializer < ActiveModel::Serializer class Location < Model
attributes :id, :time attributes :lat, :lng
associations :place
belongs_to :likeable
end end
class LocationSerializer < ActiveModel::Serializer class LocationSerializer < ActiveModel::Serializer
cache only: [:address], skip_digest: true cache only: [:address], skip_digest: true
attributes :id, :lat, :lng attributes :id, :lat, :lng
@ -165,81 +181,40 @@ class LocationSerializer < ActiveModel::Serializer
end end
end end
class Place < Model
attributes :name
associations :locations
end
class PlaceSerializer < ActiveModel::Serializer class PlaceSerializer < ActiveModel::Serializer
attributes :id, :name attributes :id, :name
has_many :locations has_many :locations
end end
class BioSerializer < ActiveModel::Serializer class Like < Model
cache except: [:content], skip_digest: true attributes :time
attributes :id, :content, :rating associations :likeable
end
belongs_to :author class LikeSerializer < ActiveModel::Serializer
attributes :id, :time
belongs_to :likeable
end end
class BlogSerializer < ActiveModel::Serializer module Spam
cache key: 'blog' class UnrelatedLink < Model
attributes :id, :name end
class UnrelatedLinkSerializer < ActiveModel::Serializer
belongs_to :writer cache only: [:id]
has_many :articles attributes :id
end
class PaginatedSerializer < ActiveModel::Serializer::CollectionSerializer
def json_key
'paginated'
end end
end end
class AlternateBlogSerializer < ActiveModel::Serializer class Tag < Model
attribute :id attributes :name
attribute :name, key: :title
end
class CustomBlogSerializer < ActiveModel::Serializer
attribute :id
attribute :special_attribute
has_many :articles
end
class CommentPreviewSerializer < ActiveModel::Serializer
attributes :id
belongs_to :post
end
class AuthorPreviewSerializer < ActiveModel::Serializer
attributes :id
has_many :posts
end
class PostPreviewSerializer < ActiveModel::Serializer
attributes :title, :body, :id
has_many :comments, serializer: CommentPreviewSerializer
belongs_to :author, serializer: AuthorPreviewSerializer
end
class PostWithTagsSerializer < ActiveModel::Serializer
attributes :id
has_many :tags
end
class PostWithCustomKeysSerializer < ActiveModel::Serializer
attributes :id
has_many :comments, key: :reviews
belongs_to :author, key: :writer
has_one :blog, key: :site
end end
class VirtualValue < Model; end
class VirtualValueSerializer < ActiveModel::Serializer class VirtualValueSerializer < ActiveModel::Serializer
attributes :id attributes :id
has_many :reviews, virtual_value: [{ type: 'reviews', id: '1' }, has_many :reviews, virtual_value: [{ type: 'reviews', id: '1' },
{ type: 'reviews', id: '2' }] { type: 'reviews', id: '2' }]
has_one :maker, virtual_value: { type: 'makers', id: '1' } has_one :maker, virtual_value: { type: 'makers', id: '1' }
@ -251,36 +226,8 @@ class VirtualValueSerializer < ActiveModel::Serializer
end end
end end
class PolymorphicHasManySerializer < ActiveModel::Serializer class PaginatedSerializer < ActiveModel::Serializer::CollectionSerializer
attributes :id, :name def json_key
end 'paginated'
class PolymorphicBelongsToSerializer < ActiveModel::Serializer
attributes :id, :title
has_one :imageable, serializer: PolymorphicHasManySerializer, polymorphic: true
end
class PolymorphicSimpleSerializer < ActiveModel::Serializer
attributes :id
end
class PolymorphicObjectTagSerializer < ActiveModel::Serializer
attributes :id
has_many :taggable, serializer: PolymorphicSimpleSerializer, polymorphic: true
end
class PolymorphicTagSerializer < ActiveModel::Serializer
attributes :id, :phrase
has_many :object_tags, serializer: PolymorphicObjectTagSerializer
end
module Spam
class UnrelatedLinkSerializer < ActiveModel::Serializer
cache only: [:id]
attributes :id
end end
end end
$VERBOSE = verbose

View File

@ -8,7 +8,7 @@ module ActiveModel
@author.roles = [] @author.roles = []
@blog = Blog.new(name: 'AMS Blog') @blog = Blog.new(name: 'AMS Blog')
@post = Post.new(title: 'New Post', body: 'Body') @post = Post.new(title: 'New Post', body: 'Body')
@tag = Tag.new(name: '#hashtagged') @tag = Tag.new(id: 'tagid', name: '#hashtagged')
@comment = Comment.new(id: 1, body: 'ZOMG A COMMENT') @comment = Comment.new(id: 1, body: 'ZOMG A COMMENT')
@post.comments = [@comment] @post.comments = [@comment]
@post.tags = [@tag] @post.tags = [@tag]
@ -53,7 +53,7 @@ module ActiveModel
assert_equal :tags, key assert_equal :tags, key
assert_nil serializer assert_nil serializer
assert_equal [{ name: '#hashtagged' }].to_json, options[:virtual_value].to_json assert_equal [{ id: 'tagid', name: '#hashtagged' }].to_json, options[:virtual_value].to_json
end end
end end
@ -62,7 +62,13 @@ module ActiveModel
.associations .associations
.detect { |assoc| assoc.key == :comments } .detect { |assoc| assoc.key == :comments }
assert association.serializer.first.custom_options[:custom_options] comment_serializer = association.serializer.first
class << comment_serializer
def custom_options
instance_options
end
end
assert comment_serializer.custom_options.fetch(:custom_options)
end end
def test_belongs_to def test_belongs_to
@ -159,7 +165,9 @@ module ActiveModel
class NamespacedResourcesTest < ActiveSupport::TestCase class NamespacedResourcesTest < ActiveSupport::TestCase
class ResourceNamespace class ResourceNamespace
class Post < ::Model; end class Post < ::Model
associations :comments, :author, :description
end
class Comment < ::Model; end class Comment < ::Model; end
class Author < ::Model; end class Author < ::Model; end
class Description < ::Model; end class Description < ::Model; end
@ -200,7 +208,9 @@ module ActiveModel
end end
class NestedSerializersTest < ActiveSupport::TestCase class NestedSerializersTest < ActiveSupport::TestCase
class Post < ::Model; end class Post < ::Model
associations :comments, :author, :description
end
class Comment < ::Model; end class Comment < ::Model; end
class Author < ::Model; end class Author < ::Model; end
class Description < ::Model; end class Description < ::Model; end
@ -240,7 +250,10 @@ module ActiveModel
# rubocop:disable Metrics/AbcSize # rubocop:disable Metrics/AbcSize
def test_conditional_associations def test_conditional_associations
model = ::Model.new(true: true, false: false) model = Class.new(::Model) do
attributes :true, :false
associations :association
end.new(true: true, false: false)
scenarios = [ scenarios = [
{ options: { if: :true }, included: true }, { options: { if: :true }, included: true },

View File

@ -81,7 +81,7 @@ module ActiveModel
assert_equal('custom', hash[:blog][:id]) assert_equal('custom', hash[:blog][:id])
end end
class PostWithVirtualAttribute < ::Model; end class PostWithVirtualAttribute < ::Model; attributes :first_name, :last_name end
class PostWithVirtualAttributeSerializer < ActiveModel::Serializer class PostWithVirtualAttributeSerializer < ActiveModel::Serializer
attribute :name do attribute :name do
"#{object.first_name} #{object.last_name}" "#{object.first_name} #{object.last_name}"
@ -98,7 +98,9 @@ module ActiveModel
# rubocop:disable Metrics/AbcSize # rubocop:disable Metrics/AbcSize
def test_conditional_associations def test_conditional_associations
model = ::Model.new(true: true, false: false) model = Class.new(::Model) do
attributes :true, :false, :attribute
end.new(true: true, false: false)
scenarios = [ scenarios = [
{ options: { if: :true }, included: true }, { options: { if: :true }, included: true },

View File

@ -3,18 +3,29 @@ require 'test_helper'
module ActiveModel module ActiveModel
class Serializer class Serializer
class OptionsTest < ActiveSupport::TestCase class OptionsTest < ActiveSupport::TestCase
def setup class ModelWithOptions < ActiveModelSerializers::Model
@profile = Profile.new(name: 'Name 1', description: 'Description 1') attributes :name, :description
end
class ModelWithOptionsSerializer < ActiveModel::Serializer
attributes :name, :description
def arguments_passed_in?
instance_options[:my_options] == :accessible
end
end
setup do
@model_with_options = ModelWithOptions.new(name: 'Name 1', description: 'Description 1')
end end
def test_options_are_accessible def test_options_are_accessible
@profile_serializer = ProfileSerializer.new(@profile, my_options: :accessible) model_with_options_serializer = ModelWithOptionsSerializer.new(@model_with_options, my_options: :accessible)
assert @profile_serializer.arguments_passed_in? assert model_with_options_serializer.arguments_passed_in?
end end
def test_no_option_is_passed_in def test_no_option_is_passed_in
@profile_serializer = ProfileSerializer.new(@profile) model_with_options_serializer = ModelWithOptionsSerializer.new(@model_with_options)
refute @profile_serializer.arguments_passed_in? refute model_with_options_serializer.arguments_passed_in?
end end
end end
end end

View File

@ -5,10 +5,10 @@ module ActiveModel
class ReadAttributeForSerializationTest < ActiveSupport::TestCase class ReadAttributeForSerializationTest < ActiveSupport::TestCase
# https://github.com/rails-api/active_model_serializers/issues/1653 # https://github.com/rails-api/active_model_serializers/issues/1653
class Parent < ActiveModelSerializers::Model class Parent < ActiveModelSerializers::Model
attr_accessor :id attributes :id
end end
class Child < Parent class Child < Parent
attr_accessor :name attributes :name
end end
class ParentSerializer < ActiveModel::Serializer class ParentSerializer < ActiveModel::Serializer
attributes :$id attributes :$id
@ -30,7 +30,7 @@ module ActiveModel
# https://github.com/rails-api/active_model_serializers/issues/1658 # https://github.com/rails-api/active_model_serializers/issues/1658
class ErrorResponse < ActiveModelSerializers::Model class ErrorResponse < ActiveModelSerializers::Model
attr_accessor :error attributes :error
end end
class ApplicationSerializer < ActiveModel::Serializer class ApplicationSerializer < ActiveModel::Serializer
attributes :status attributes :status

View File

@ -2,10 +2,10 @@ module ActiveModel
class Serializer class Serializer
class SerializationTest < ActiveSupport::TestCase class SerializationTest < ActiveSupport::TestCase
class Blog < ActiveModelSerializers::Model class Blog < ActiveModelSerializers::Model
attr_accessor :id, :name, :authors attributes :id, :name, :authors
end end
class Author < ActiveModelSerializers::Model class Author < ActiveModelSerializers::Model
attr_accessor :id, :name attributes :id, :name
end end
class BlogSerializer < ActiveModel::Serializer class BlogSerializer < ActiveModel::Serializer
attributes :id attributes :id

View File

@ -3,9 +3,12 @@ require 'test_helper'
module ActiveModel module ActiveModel
class Serializer class Serializer
class SerializerForWithNamespaceTest < ActiveSupport::TestCase class SerializerForWithNamespaceTest < ActiveSupport::TestCase
class Book < ::Model; end class Book < ::Model
class Page < ::Model; end attributes :title, :author_name
class Publisher < ::Model; end associations :publisher, :pages
end
class Page < ::Model; attributes :number, :text end
class Publisher < ::Model; attributes :name end
module Api module Api
module V3 module V3
@ -18,8 +21,6 @@ module ActiveModel
class PageSerializer < ActiveModel::Serializer class PageSerializer < ActiveModel::Serializer
attributes :number, :text attributes :number, :text
belongs_to :book
end end
class PublisherSerializer < ActiveModel::Serializer class PublisherSerializer < ActiveModel::Serializer