mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-23 06:16:50 +00:00
Add Model#attributes helper; make test attributes explicit
This commit is contained in:
parent
85dfef9072
commit
d5babdd060
@ -6,10 +6,14 @@ Breaking changes:
|
||||
|
||||
Features:
|
||||
|
||||
- [#2021](https://github.com/rails-api/active_model_serializers/pull/2021) ActiveModelSerializers::Model#attributes. (@bf4)
|
||||
|
||||
Fixes:
|
||||
|
||||
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)
|
||||
|
||||
Misc:
|
||||
|
||||
@ -116,7 +116,7 @@ class SomeResource < ActiveRecord::Base
|
||||
end
|
||||
# or
|
||||
class SomeResource < ActiveModelSerializers::Model
|
||||
attr_accessor :title, :body
|
||||
attributes :title, :body
|
||||
end
|
||||
```
|
||||
|
||||
@ -279,7 +279,7 @@ which is a simple serializable PORO (Plain-Old Ruby Object).
|
||||
|
||||
```ruby
|
||||
class MyModel < ActiveModelSerializers::Model
|
||||
attr_accessor :id, :name, :level
|
||||
attributes :id, :name, :level
|
||||
end
|
||||
```
|
||||
|
||||
|
||||
@ -2,7 +2,10 @@
|
||||
|
||||
# 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
|
||||
# my_model.rb
|
||||
class MyModel
|
||||
@ -21,12 +24,22 @@ class MyModel
|
||||
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
|
||||
# my_model.rb
|
||||
class MyModel < ActiveModelSerializers::Model
|
||||
attr_accessor :id, :name, :level
|
||||
attributes :id, :name, :level
|
||||
end
|
||||
```
|
||||
|
||||
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).
|
||||
|
||||
@ -38,6 +38,14 @@ module ActiveModelSerializers
|
||||
@default_include_directive ||= JSONAPI::IncludeDirective.new(config.default_includes, allow_wildcard: true)
|
||||
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'
|
||||
require 'active_model/serializable_resource'
|
||||
|
||||
@ -1,40 +1,92 @@
|
||||
# ActiveModelSerializers::Model is a convenient
|
||||
# serializable class to inherit from when making
|
||||
# serializable non-activerecord objects.
|
||||
# ActiveModelSerializers::Model is a convenient superclass for making your models
|
||||
# from Plain-Old Ruby Objects (PORO). It also serves as a reference implementation
|
||||
# that satisfies ActiveModel::Serializer::Lint::Tests.
|
||||
module ActiveModelSerializers
|
||||
class Model
|
||||
include ActiveModel::Model
|
||||
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 = {})
|
||||
@attributes = attributes && attributes.symbolize_keys
|
||||
attributes ||= {} # protect against nil
|
||||
@attributes = attributes.symbolize_keys.with_indifferent_access
|
||||
@errors = ActiveModel::Errors.new(self)
|
||||
super
|
||||
end
|
||||
|
||||
# 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
|
||||
attributes.fetch(:id) { self.class.name.downcase }
|
||||
attributes.fetch(:id) do
|
||||
defined?(@id) ? @id : self.class.model_name.name && self.class.model_name.name.downcase
|
||||
end
|
||||
end
|
||||
|
||||
# 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.
|
||||
# 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) { File.mtime(__FILE__) }
|
||||
attributes.fetch(:updated_at) do
|
||||
defined?(@updated_at) ? @updated_at : File.mtime(__FILE__)
|
||||
end
|
||||
end
|
||||
|
||||
def read_attribute_for_serialization(key)
|
||||
if key == :id || key == 'id'
|
||||
attributes.fetch(key) { id }
|
||||
else
|
||||
attributes[key]
|
||||
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
|
||||
|
||||
@ -15,7 +15,7 @@ module ActionController
|
||||
end
|
||||
|
||||
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
|
||||
end
|
||||
end
|
||||
@ -46,7 +46,7 @@ module ActionController
|
||||
|
||||
def test_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
|
||||
|
||||
@ -5,7 +5,16 @@ module ActionController
|
||||
class JsonApi
|
||||
class FieldsTest < ActionController::TestCase
|
||||
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'
|
||||
attributes :title, :body, :publish_at
|
||||
belongs_to :author
|
||||
@ -14,10 +23,10 @@ module ActionController
|
||||
|
||||
def setup_post
|
||||
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)
|
||||
@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],
|
||||
publish_at: '2020-03-16T03:55:25.291Z')
|
||||
@comment1.post = @post
|
||||
@ -26,7 +35,7 @@ module ActionController
|
||||
|
||||
def render_fields_works_on_relationships
|
||||
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
|
||||
|
||||
|
||||
@ -5,9 +5,17 @@ module ActionController
|
||||
class JsonApi
|
||||
class KeyTransformTest < ActionController::TestCase
|
||||
class KeyTransformTestController < ActionController::Base
|
||||
class Post < ::Model; end
|
||||
class Author < ::Model; end
|
||||
class TopComment < ::Model; end
|
||||
class Post < ::Model
|
||||
attributes :title, :body, :publish_at
|
||||
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
|
||||
type 'posts'
|
||||
attributes :title, :body, :publish_at
|
||||
|
||||
@ -3,10 +3,16 @@ require 'test_helper'
|
||||
module ActionController
|
||||
module Serialization
|
||||
class NamespaceLookupTest < ActionController::TestCase
|
||||
class Book < ::Model; end
|
||||
class Page < ::Model; end
|
||||
class Chapter < ::Model; end
|
||||
class Writer < ::Model; end
|
||||
class Book < ::Model
|
||||
attributes :title, :body
|
||||
associations :writer, :chapters
|
||||
end
|
||||
class Chapter < ::Model
|
||||
attributes :title
|
||||
end
|
||||
class Writer < ::Model
|
||||
attributes :name
|
||||
end
|
||||
|
||||
module Api
|
||||
module V2
|
||||
@ -93,7 +99,7 @@ module ActionController
|
||||
end
|
||||
|
||||
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
|
||||
end
|
||||
@ -205,7 +211,7 @@ module ActionController
|
||||
|
||||
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)
|
||||
|
||||
assert_equal expected, actual
|
||||
|
||||
@ -2,16 +2,16 @@ require 'test_helper'
|
||||
|
||||
module SerializationScopeTesting
|
||||
class User < ActiveModelSerializers::Model
|
||||
attr_accessor :id, :name, :admin
|
||||
attributes :id, :name, :admin
|
||||
def admin?
|
||||
admin
|
||||
end
|
||||
end
|
||||
class Comment < ActiveModelSerializers::Model
|
||||
attr_accessor :id, :body
|
||||
attributes :id, :body
|
||||
end
|
||||
class Post < ActiveModelSerializers::Model
|
||||
attr_accessor :id, :title, :body, :comments
|
||||
attributes :id, :title, :body, :comments
|
||||
end
|
||||
class PostSerializer < ActiveModel::Serializer
|
||||
attributes :id, :title, :body, :comments
|
||||
|
||||
@ -135,7 +135,7 @@ module ActionController
|
||||
like = Like.new(id: 1, likeable: comment, time: 3.days.ago)
|
||||
|
||||
generate_cached_serializer(like)
|
||||
like.likable = comment2
|
||||
like.likeable = comment2
|
||||
like.time = Time.zone.now.to_s
|
||||
|
||||
render json: like
|
||||
|
||||
@ -4,13 +4,13 @@ module ActiveModelSerializers
|
||||
class ModelTest < ActiveSupport::TestCase
|
||||
include ActiveModel::Serializer::Lint::Tests
|
||||
|
||||
def setup
|
||||
setup do
|
||||
@resource = ActiveModelSerializers::Model.new
|
||||
end
|
||||
|
||||
def test_initialization_with_string_keys
|
||||
klass = Class.new(ActiveModelSerializers::Model) do
|
||||
attr_accessor :key
|
||||
attributes :key
|
||||
end
|
||||
value = 'value'
|
||||
|
||||
@ -18,5 +18,68 @@ module ActiveModelSerializers
|
||||
|
||||
assert_equal model_instance.read_attribute_for_serialization(:key), value
|
||||
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
|
||||
|
||||
@ -44,7 +44,7 @@ class JsonApiRendererTest < ActionDispatch::IntegrationTest
|
||||
|
||||
def define_author_model_and_serializer
|
||||
TestController.const_set(:Author, Class.new(ActiveModelSerializers::Model) do
|
||||
attr_accessor :id, :name
|
||||
attributes :id, :name
|
||||
end)
|
||||
TestController.const_set(:AuthorSerializer, Class.new(ActiveModel::Serializer) do
|
||||
type 'users'
|
||||
|
||||
@ -3,11 +3,8 @@ require 'test_helper'
|
||||
module ActiveModelSerializers
|
||||
module Adapter
|
||||
class AttributesTest < ActiveSupport::TestCase
|
||||
class Person
|
||||
include ActiveModel::Model
|
||||
include ActiveModel::Serialization
|
||||
|
||||
attr_accessor :first_name, :last_name
|
||||
class Person < ActiveModelSerializers::Model
|
||||
attributes :first_name, :last_name
|
||||
end
|
||||
|
||||
class PersonSerializer < ActiveModel::Serializer
|
||||
|
||||
@ -4,9 +4,17 @@ module ActiveModelSerializers
|
||||
module Adapter
|
||||
class JsonApi
|
||||
class FieldsTest < ActiveSupport::TestCase
|
||||
class Post < ::Model; end
|
||||
class Author < ::Model; end
|
||||
class Comment < ::Model; end
|
||||
class Post < ::Model
|
||||
attributes :title, :body
|
||||
associations :author, :comments
|
||||
end
|
||||
class Author < ::Model
|
||||
attributes :name, :birthday
|
||||
end
|
||||
class Comment < ::Model
|
||||
attributes :body
|
||||
associations :author, :post
|
||||
end
|
||||
|
||||
class PostSerializer < ActiveModel::Serializer
|
||||
type 'posts'
|
||||
|
||||
@ -5,7 +5,9 @@ module ActiveModel
|
||||
module Adapter
|
||||
class JsonApi
|
||||
class IncludeParamTest < ActiveSupport::TestCase
|
||||
IncludeParamAuthor = Class.new(::Model)
|
||||
IncludeParamAuthor = Class.new(::Model) do
|
||||
associations :tags, :posts
|
||||
end
|
||||
|
||||
class CustomCommentLoader
|
||||
def all
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
require 'test_helper'
|
||||
|
||||
class NestedPost < ::Model; end
|
||||
class NestedPost < ::Model; associations :nested_posts end
|
||||
class NestedPostSerializer < ActiveModel::Serializer
|
||||
has_many :nested_posts
|
||||
end
|
||||
@ -301,8 +301,8 @@ module ActiveModelSerializers
|
||||
end
|
||||
|
||||
class NoDuplicatesTest < ActiveSupport::TestCase
|
||||
class Post < ::Model; end
|
||||
class Author < ::Model; end
|
||||
class Post < ::Model; associations :author end
|
||||
class Author < ::Model; associations :posts, :roles, :bio end
|
||||
|
||||
class PostSerializer < ActiveModel::Serializer
|
||||
type 'posts'
|
||||
|
||||
@ -4,7 +4,7 @@ module ActiveModelSerializers
|
||||
module Adapter
|
||||
class JsonApi
|
||||
class LinksTest < ActiveSupport::TestCase
|
||||
class LinkAuthor < ::Model; end
|
||||
class LinkAuthor < ::Model; associations :posts end
|
||||
class LinkAuthorSerializer < ActiveModel::Serializer
|
||||
link :self do
|
||||
href "http://example.com/link_author/#{object.id}"
|
||||
|
||||
@ -384,7 +384,7 @@ module ActiveModelSerializers
|
||||
|
||||
def new_model(model_attributes)
|
||||
Class.new(ActiveModelSerializers::Model) do
|
||||
attr_accessor(*model_attributes.keys)
|
||||
attributes(*model_attributes.keys)
|
||||
|
||||
def self.name
|
||||
'TestModel'
|
||||
|
||||
@ -4,9 +4,17 @@ module ActiveModelSerializers
|
||||
module Adapter
|
||||
class JsonApi
|
||||
class KeyCaseTest < ActiveSupport::TestCase
|
||||
class Post < ::Model; end
|
||||
class Author < ::Model; end
|
||||
class Comment < ::Model; end
|
||||
class Post < ::Model
|
||||
attributes :title, :body, :publish_at
|
||||
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
|
||||
type 'posts'
|
||||
|
||||
@ -34,6 +34,7 @@ module ActiveModelSerializers
|
||||
end
|
||||
|
||||
class Article < ::Model
|
||||
attributes :title
|
||||
# To confirm error is raised when cache_key is not set and cache_key option not passed to cache
|
||||
undef_method :cache_key
|
||||
end
|
||||
@ -48,6 +49,16 @@ module ActiveModelSerializers
|
||||
attribute :special_attribute
|
||||
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
|
||||
cache_store.clear
|
||||
@comment = Comment.new(id: 1, body: 'ZOMG A COMMENT')
|
||||
@ -244,7 +255,7 @@ module ActiveModelSerializers
|
||||
# rubocop:disable Metrics/AbcSize
|
||||
def test_a_serializer_rendered_by_two_adapter_returns_differently_fetch_attributes
|
||||
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)
|
||||
Object.const_set(:UncachedAlertSerializer, Class.new(ActiveModel::Serializer) do
|
||||
attributes :id, :status, :resource, :started_at, :ended_at, :updated_at, :created_at
|
||||
@ -271,7 +282,7 @@ module ActiveModelSerializers
|
||||
ended_at: nil,
|
||||
updated_at: alert.updated_at,
|
||||
created_at: alert.created_at
|
||||
}
|
||||
}.with_indifferent_access
|
||||
expected_cached_jsonapi_attributes = {
|
||||
id: '1',
|
||||
type: 'alerts',
|
||||
@ -283,15 +294,15 @@ module ActiveModelSerializers
|
||||
updated_at: alert.updated_at,
|
||||
created_at: alert.created_at
|
||||
}
|
||||
}
|
||||
}.with_indifferent_access
|
||||
|
||||
# Assert attributes are serialized correctly
|
||||
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 alert.attributes, attributes_serialization
|
||||
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)
|
||||
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)
|
||||
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
|
||||
ensure
|
||||
Object.send(:remove_const, :Alert)
|
||||
@ -329,11 +340,15 @@ module ActiveModelSerializers
|
||||
actual = ActiveModel::Serializer.object_cache_keys(serializable.adapter.serializer, serializable.adapter, include_directive)
|
||||
|
||||
assert_equal 3, actual.size
|
||||
assert actual.any? { |key| key == "comment/1/#{serializable.adapter.cache_key}" }
|
||||
assert actual.any? { |key| key =~ %r{post/post-\d+} }
|
||||
assert actual.any? { |key| key =~ %r{author/author-\d+} }
|
||||
expected_key = "comment/1/#{serializable.adapter.cache_key}"
|
||||
assert actual.any? { |key| key == expected_key }, "actual '#{actual}' should include #{expected_key}"
|
||||
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
|
||||
|
||||
# rubocop:disable Metrics/AbcSize
|
||||
def test_fetch_attributes_from_cache
|
||||
serializers = ActiveModel::Serializer::CollectionSerializer.new([@comment, @comment])
|
||||
|
||||
@ -344,10 +359,10 @@ module ActiveModelSerializers
|
||||
adapter_options = {}
|
||||
adapter_instance = ActiveModelSerializers::Adapter::Attributes.new(serializers, adapter_options)
|
||||
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
|
||||
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 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
|
||||
end
|
||||
end
|
||||
# rubocop:enable Metrics/AbcSize
|
||||
|
||||
def test_cache_read_multi_with_fragment_cache_enabled
|
||||
post_serializer = Class.new(ActiveModel::Serializer) do
|
||||
|
||||
@ -3,14 +3,27 @@ require 'test_helper'
|
||||
module ActiveModel
|
||||
class Serializer
|
||||
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
|
||||
type 'messages'
|
||||
end
|
||||
|
||||
def setup
|
||||
@comment = Comment.new
|
||||
@post = Post.new
|
||||
@resource = build_named_collection @comment, @post
|
||||
@singular_model = SingularModel.new
|
||||
@has_many_model = HasManyModel.new
|
||||
@resource = build_named_collection @singular_model, @has_many_model
|
||||
@serializer = collection_serializer.new(@resource, some: :options)
|
||||
end
|
||||
|
||||
@ -34,29 +47,29 @@ module ActiveModel
|
||||
def test_each_object_should_be_serialized_with_appropriate_serializer
|
||||
serializers = @serializer.to_a
|
||||
|
||||
assert_kind_of CommentSerializer, serializers.first
|
||||
assert_kind_of Comment, serializers.first.object
|
||||
assert_kind_of SingularModelSerializer, serializers.first
|
||||
assert_kind_of SingularModel, serializers.first.object
|
||||
|
||||
assert_kind_of PostSerializer, serializers.last
|
||||
assert_kind_of Post, serializers.last.object
|
||||
assert_kind_of HasManyModelSerializer, serializers.last
|
||||
assert_kind_of HasManyModel, serializers.last.object
|
||||
|
||||
assert_equal :options, serializers.last.custom_options[:some]
|
||||
end
|
||||
|
||||
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)
|
||||
end
|
||||
|
||||
def test_root_default
|
||||
@serializer = collection_serializer.new([@comment, @post])
|
||||
@serializer = collection_serializer.new([@singular_model, @has_many_model])
|
||||
assert_nil @serializer.root
|
||||
end
|
||||
|
||||
def test_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
|
||||
end
|
||||
|
||||
|
||||
55
test/fixtures/active_record.rb
vendored
55
test/fixtures/active_record.rb
vendored
@ -47,16 +47,6 @@ module ARModels
|
||||
has_many :comments
|
||||
belongs_to :author
|
||||
end
|
||||
|
||||
class Comment < ActiveRecord::Base
|
||||
belongs_to :post
|
||||
belongs_to :author
|
||||
end
|
||||
|
||||
class Author < ActiveRecord::Base
|
||||
has_many :posts
|
||||
end
|
||||
|
||||
class PostSerializer < ActiveModel::Serializer
|
||||
attributes :id, :title, :body
|
||||
|
||||
@ -64,15 +54,60 @@ module ARModels
|
||||
belongs_to :author
|
||||
end
|
||||
|
||||
class Comment < ActiveRecord::Base
|
||||
belongs_to :post
|
||||
belongs_to :author
|
||||
end
|
||||
class CommentSerializer < ActiveModel::Serializer
|
||||
attributes :id, :contents
|
||||
|
||||
belongs_to :author
|
||||
end
|
||||
|
||||
class Author < ActiveRecord::Base
|
||||
has_many :posts
|
||||
end
|
||||
class AuthorSerializer < ActiveModel::Serializer
|
||||
attributes :id, :name
|
||||
|
||||
has_many :posts
|
||||
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
|
||||
|
||||
305
test/fixtures/poro.rb
vendored
305
test/fixtures/poro.rb
vendored
@ -1,25 +1,28 @@
|
||||
verbose = $VERBOSE
|
||||
$VERBOSE = nil
|
||||
class Model < ActiveModelSerializers::Model
|
||||
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
|
||||
def method_missing(meth, *args)
|
||||
if meth.to_s =~ /^(.*)=$/
|
||||
attributes[Regexp.last_match(1).to_sym] = args[0]
|
||||
elsif attributes.key?(meth)
|
||||
attributes[meth]
|
||||
else
|
||||
super
|
||||
# At this time, just for organization of intent
|
||||
class_attribute :association_names
|
||||
self.association_names = []
|
||||
|
||||
def self.associations(*names)
|
||||
self.association_names |= names.map(&:to_sym)
|
||||
# Silence redefinition of methods warnings
|
||||
ActiveModelSerializers.silence_warnings do
|
||||
attr_accessor(*names)
|
||||
end
|
||||
end
|
||||
|
||||
# required for ActiveModel::AttributeAssignment#_assign_attribute
|
||||
# in Rails 5
|
||||
def respond_to_missing?(method_name, _include_private = false)
|
||||
attributes.key?(method_name.to_s.tr('=', '').to_sym) || super
|
||||
def associations
|
||||
association_names.each_with_object({}) do |association_name, result|
|
||||
result[association_name] = public_send(association_name).freeze
|
||||
end.with_indifferent_access.freeze
|
||||
end
|
||||
|
||||
def attributes
|
||||
super.except(*association_names)
|
||||
end
|
||||
end
|
||||
|
||||
@ -30,67 +33,59 @@ end
|
||||
# model = ModelWithErrors.new
|
||||
# model.validate! # => ["cannot be nil"]
|
||||
# model.errors.full_messages # => ["name cannot be nil"]
|
||||
class ModelWithErrors < ::ActiveModelSerializers::Model
|
||||
attr_accessor :name
|
||||
class ModelWithErrors < Model
|
||||
attributes :name
|
||||
end
|
||||
|
||||
class Profile < Model
|
||||
attributes :name, :description
|
||||
associations :comments
|
||||
end
|
||||
|
||||
class ProfileSerializer < ActiveModel::Serializer
|
||||
attributes :name, :description
|
||||
|
||||
# TODO: is this used anywhere?
|
||||
def arguments_passed_in?
|
||||
instance_options[:my_options] == :accessible
|
||||
end
|
||||
end
|
||||
|
||||
class ProfilePreviewSerializer < ActiveModel::Serializer
|
||||
attributes :name
|
||||
end
|
||||
|
||||
class Post < Model; end
|
||||
class Like < Model; end
|
||||
class Author < Model; end
|
||||
class Bio < Model; end
|
||||
class Blog < Model; end
|
||||
class Role < Model; end
|
||||
class User < Model; end
|
||||
class Location < Model; end
|
||||
class Place < Model; end
|
||||
class Tag < Model; end
|
||||
class VirtualValue < Model; end
|
||||
class Author < Model
|
||||
attributes :name
|
||||
associations :posts, :bio, :roles, :comments
|
||||
end
|
||||
class AuthorSerializer < ActiveModel::Serializer
|
||||
cache key: 'writer', skip_digest: true
|
||||
attribute :id
|
||||
attribute :name
|
||||
|
||||
has_many :posts
|
||||
has_many :roles
|
||||
has_one :bio
|
||||
end
|
||||
class AuthorPreviewSerializer < ActiveModel::Serializer
|
||||
attributes :id
|
||||
has_many :posts
|
||||
end
|
||||
|
||||
class Comment < Model
|
||||
# Uses a custom non-time-based cache key
|
||||
def cache_key
|
||||
"#{self.class.name.downcase}/#{id}"
|
||||
attributes :body, :date
|
||||
associations :post, :author, :likes
|
||||
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
|
||||
|
||||
class Employee < ActiveRecord::Base
|
||||
has_many :pictures, as: :imageable
|
||||
has_many :object_tags, as: :taggable
|
||||
class Post < Model
|
||||
attributes :title, :body
|
||||
associations :author, :comments, :blog, :tags, :related
|
||||
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
|
||||
cache key: 'post', expires_in: 0.1, skip_digest: true
|
||||
attributes :id, :title, :body
|
||||
@ -102,58 +97,79 @@ class PostSerializer < ActiveModel::Serializer
|
||||
def blog
|
||||
Blog.new(id: 999, name: 'Custom blog')
|
||||
end
|
||||
|
||||
# TODO: is this used anywhere?
|
||||
def custom_options
|
||||
instance_options
|
||||
end
|
||||
end
|
||||
|
||||
class SpammyPostSerializer < ActiveModel::Serializer
|
||||
attributes :id
|
||||
has_many :related
|
||||
end
|
||||
class PostPreviewSerializer < ActiveModel::Serializer
|
||||
attributes :title, :body, :id
|
||||
|
||||
class CommentSerializer < ActiveModel::Serializer
|
||||
cache expires_in: 1.day, skip_digest: true
|
||||
attributes :id, :body
|
||||
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
|
||||
|
||||
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
|
||||
|
||||
def custom_options
|
||||
instance_options
|
||||
end
|
||||
end
|
||||
|
||||
class AuthorSerializer < ActiveModel::Serializer
|
||||
cache key: 'writer', skip_digest: true
|
||||
class Blog < Model
|
||||
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 :name
|
||||
|
||||
has_many :posts
|
||||
has_many :roles
|
||||
has_one :bio
|
||||
attribute :name, key: :title
|
||||
end
|
||||
class CustomBlogSerializer < ActiveModel::Serializer
|
||||
attribute :id
|
||||
attribute :special_attribute
|
||||
has_many :articles
|
||||
end
|
||||
|
||||
class Role < Model
|
||||
attributes :name, :description, :special_attribute
|
||||
associations :author
|
||||
end
|
||||
class RoleSerializer < ActiveModel::Serializer
|
||||
cache only: [:name, :slug], skip_digest: true
|
||||
attributes :id, :name, :description
|
||||
attribute :friendly_id, key: :slug
|
||||
belongs_to :author
|
||||
|
||||
def friendly_id
|
||||
"#{object.name}-#{object.id}"
|
||||
end
|
||||
|
||||
belongs_to :author
|
||||
end
|
||||
|
||||
class LikeSerializer < ActiveModel::Serializer
|
||||
attributes :id, :time
|
||||
|
||||
belongs_to :likeable
|
||||
class Location < Model
|
||||
attributes :lat, :lng
|
||||
associations :place
|
||||
end
|
||||
|
||||
class LocationSerializer < ActiveModel::Serializer
|
||||
cache only: [:address], skip_digest: true
|
||||
attributes :id, :lat, :lng
|
||||
@ -165,81 +181,40 @@ class LocationSerializer < ActiveModel::Serializer
|
||||
end
|
||||
end
|
||||
|
||||
class Place < Model
|
||||
attributes :name
|
||||
associations :locations
|
||||
end
|
||||
class PlaceSerializer < ActiveModel::Serializer
|
||||
attributes :id, :name
|
||||
|
||||
has_many :locations
|
||||
end
|
||||
|
||||
class BioSerializer < ActiveModel::Serializer
|
||||
cache except: [:content], skip_digest: true
|
||||
attributes :id, :content, :rating
|
||||
|
||||
belongs_to :author
|
||||
class Like < Model
|
||||
attributes :time
|
||||
associations :likeable
|
||||
end
|
||||
class LikeSerializer < ActiveModel::Serializer
|
||||
attributes :id, :time
|
||||
belongs_to :likeable
|
||||
end
|
||||
|
||||
class BlogSerializer < ActiveModel::Serializer
|
||||
cache key: 'blog'
|
||||
attributes :id, :name
|
||||
|
||||
belongs_to :writer
|
||||
has_many :articles
|
||||
module Spam
|
||||
class UnrelatedLink < Model
|
||||
end
|
||||
|
||||
class PaginatedSerializer < ActiveModel::Serializer::CollectionSerializer
|
||||
def json_key
|
||||
'paginated'
|
||||
end
|
||||
end
|
||||
|
||||
class AlternateBlogSerializer < ActiveModel::Serializer
|
||||
attribute :id
|
||||
attribute :name, key: :title
|
||||
end
|
||||
|
||||
class CustomBlogSerializer < ActiveModel::Serializer
|
||||
attribute :id
|
||||
attribute :special_attribute
|
||||
|
||||
has_many :articles
|
||||
end
|
||||
|
||||
class CommentPreviewSerializer < ActiveModel::Serializer
|
||||
class UnrelatedLinkSerializer < ActiveModel::Serializer
|
||||
cache only: [:id]
|
||||
attributes :id
|
||||
|
||||
belongs_to :post
|
||||
end
|
||||
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
|
||||
class Tag < Model
|
||||
attributes :name
|
||||
end
|
||||
|
||||
class VirtualValue < Model; end
|
||||
class VirtualValueSerializer < ActiveModel::Serializer
|
||||
attributes :id
|
||||
|
||||
has_many :reviews, virtual_value: [{ type: 'reviews', id: '1' },
|
||||
{ type: 'reviews', id: '2' }]
|
||||
has_one :maker, virtual_value: { type: 'makers', id: '1' }
|
||||
@ -251,36 +226,8 @@ class VirtualValueSerializer < ActiveModel::Serializer
|
||||
end
|
||||
end
|
||||
|
||||
class PolymorphicHasManySerializer < ActiveModel::Serializer
|
||||
attributes :id, :name
|
||||
end
|
||||
|
||||
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
|
||||
class PaginatedSerializer < ActiveModel::Serializer::CollectionSerializer
|
||||
def json_key
|
||||
'paginated'
|
||||
end
|
||||
end
|
||||
$VERBOSE = verbose
|
||||
|
||||
@ -8,7 +8,7 @@ module ActiveModel
|
||||
@author.roles = []
|
||||
@blog = Blog.new(name: 'AMS Blog')
|
||||
@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')
|
||||
@post.comments = [@comment]
|
||||
@post.tags = [@tag]
|
||||
@ -53,7 +53,7 @@ module ActiveModel
|
||||
|
||||
assert_equal :tags, key
|
||||
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
|
||||
|
||||
@ -62,7 +62,13 @@ module ActiveModel
|
||||
.associations
|
||||
.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
|
||||
|
||||
def test_belongs_to
|
||||
@ -159,7 +165,9 @@ module ActiveModel
|
||||
|
||||
class NamespacedResourcesTest < ActiveSupport::TestCase
|
||||
class ResourceNamespace
|
||||
class Post < ::Model; end
|
||||
class Post < ::Model
|
||||
associations :comments, :author, :description
|
||||
end
|
||||
class Comment < ::Model; end
|
||||
class Author < ::Model; end
|
||||
class Description < ::Model; end
|
||||
@ -200,7 +208,9 @@ module ActiveModel
|
||||
end
|
||||
|
||||
class NestedSerializersTest < ActiveSupport::TestCase
|
||||
class Post < ::Model; end
|
||||
class Post < ::Model
|
||||
associations :comments, :author, :description
|
||||
end
|
||||
class Comment < ::Model; end
|
||||
class Author < ::Model; end
|
||||
class Description < ::Model; end
|
||||
@ -240,7 +250,10 @@ module ActiveModel
|
||||
|
||||
# rubocop:disable Metrics/AbcSize
|
||||
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 = [
|
||||
{ options: { if: :true }, included: true },
|
||||
|
||||
@ -81,7 +81,7 @@ module ActiveModel
|
||||
assert_equal('custom', hash[:blog][:id])
|
||||
end
|
||||
|
||||
class PostWithVirtualAttribute < ::Model; end
|
||||
class PostWithVirtualAttribute < ::Model; attributes :first_name, :last_name end
|
||||
class PostWithVirtualAttributeSerializer < ActiveModel::Serializer
|
||||
attribute :name do
|
||||
"#{object.first_name} #{object.last_name}"
|
||||
@ -98,7 +98,9 @@ module ActiveModel
|
||||
|
||||
# rubocop:disable Metrics/AbcSize
|
||||
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 = [
|
||||
{ options: { if: :true }, included: true },
|
||||
|
||||
@ -3,18 +3,29 @@ require 'test_helper'
|
||||
module ActiveModel
|
||||
class Serializer
|
||||
class OptionsTest < ActiveSupport::TestCase
|
||||
def setup
|
||||
@profile = Profile.new(name: 'Name 1', description: 'Description 1')
|
||||
class ModelWithOptions < ActiveModelSerializers::Model
|
||||
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
|
||||
|
||||
def test_options_are_accessible
|
||||
@profile_serializer = ProfileSerializer.new(@profile, my_options: :accessible)
|
||||
assert @profile_serializer.arguments_passed_in?
|
||||
model_with_options_serializer = ModelWithOptionsSerializer.new(@model_with_options, my_options: :accessible)
|
||||
assert model_with_options_serializer.arguments_passed_in?
|
||||
end
|
||||
|
||||
def test_no_option_is_passed_in
|
||||
@profile_serializer = ProfileSerializer.new(@profile)
|
||||
refute @profile_serializer.arguments_passed_in?
|
||||
model_with_options_serializer = ModelWithOptionsSerializer.new(@model_with_options)
|
||||
refute model_with_options_serializer.arguments_passed_in?
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@ -5,10 +5,10 @@ module ActiveModel
|
||||
class ReadAttributeForSerializationTest < ActiveSupport::TestCase
|
||||
# https://github.com/rails-api/active_model_serializers/issues/1653
|
||||
class Parent < ActiveModelSerializers::Model
|
||||
attr_accessor :id
|
||||
attributes :id
|
||||
end
|
||||
class Child < Parent
|
||||
attr_accessor :name
|
||||
attributes :name
|
||||
end
|
||||
class ParentSerializer < ActiveModel::Serializer
|
||||
attributes :$id
|
||||
@ -30,7 +30,7 @@ module ActiveModel
|
||||
|
||||
# https://github.com/rails-api/active_model_serializers/issues/1658
|
||||
class ErrorResponse < ActiveModelSerializers::Model
|
||||
attr_accessor :error
|
||||
attributes :error
|
||||
end
|
||||
class ApplicationSerializer < ActiveModel::Serializer
|
||||
attributes :status
|
||||
|
||||
@ -2,10 +2,10 @@ module ActiveModel
|
||||
class Serializer
|
||||
class SerializationTest < ActiveSupport::TestCase
|
||||
class Blog < ActiveModelSerializers::Model
|
||||
attr_accessor :id, :name, :authors
|
||||
attributes :id, :name, :authors
|
||||
end
|
||||
class Author < ActiveModelSerializers::Model
|
||||
attr_accessor :id, :name
|
||||
attributes :id, :name
|
||||
end
|
||||
class BlogSerializer < ActiveModel::Serializer
|
||||
attributes :id
|
||||
|
||||
@ -3,9 +3,12 @@ require 'test_helper'
|
||||
module ActiveModel
|
||||
class Serializer
|
||||
class SerializerForWithNamespaceTest < ActiveSupport::TestCase
|
||||
class Book < ::Model; end
|
||||
class Page < ::Model; end
|
||||
class Publisher < ::Model; end
|
||||
class Book < ::Model
|
||||
attributes :title, :author_name
|
||||
associations :publisher, :pages
|
||||
end
|
||||
class Page < ::Model; attributes :number, :text end
|
||||
class Publisher < ::Model; attributes :name end
|
||||
|
||||
module Api
|
||||
module V3
|
||||
@ -18,8 +21,6 @@ module ActiveModel
|
||||
|
||||
class PageSerializer < ActiveModel::Serializer
|
||||
attributes :number, :text
|
||||
|
||||
belongs_to :book
|
||||
end
|
||||
|
||||
class PublisherSerializer < ActiveModel::Serializer
|
||||
|
||||
Loading…
Reference in New Issue
Block a user