Make test attributes explicit

- Organize test poros with associations and by serializer
- Freeze derived attributes/associations against mutation
- Cleanup PORO fixtures
This commit is contained in:
Benjamin Fleischer 2016-11-21 09:31:11 -06:00
parent 095ad9c82c
commit 80af763d2e
20 changed files with 380 additions and 278 deletions

View File

@ -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'

View File

@ -3,42 +3,58 @@
# serializable non-activerecord objects.
module ActiveModelSerializers
class Model
include ActiveModel::Model
include ActiveModel::Serializers::JSON
include ActiveModel::Model
class_attribute :attribute_names
# Initialize +attribute_names+ for all subclasses. The array is usually
# mutated in the +attributes+ method, but can be set directly, as well.
self.attribute_names = []
def self.attributes(*names)
attr_accessor(*names)
self.attribute_names |= names.map(&:to_sym)
# Silence redefinition of methods warnings
ActiveModelSerializers.silence_warnings do
attr_accessor(*names)
end
end
attr_reader :attributes, :errors
attr_reader :errors
# NOTE that +updated_at+ isn't included in +attribute_names+,
# which means it won't show up in +attributes+ unless a subclass has
# either <tt>attributes :updated_at</tt> which will redefine the methods
# or <tt>attribute_names << :updated_at</tt>.
attr_writer :updated_at
# NOTE that +id+ will always be in +attributes+.
attributes :id
def initialize(attributes = {})
@attributes = attributes && attributes.symbolize_keys
@errors = ActiveModel::Errors.new(self)
super
end
# Defaults to the downcased model name.
def id
attributes.fetch(:id) { self.class.name.downcase }
# The the fields in +attribute_names+ determines the returned hash.
# +attributes+ are returned frozen to prevent any expectations that mutation affects
# the actual values in the model.
def attributes
attribute_names.each_with_object({}) do |attribute_name, result|
result[attribute_name] = public_send(attribute_name).freeze
end.with_indifferent_access.freeze
end
# Defaults to the downcased model name and updated_at
# To customize model behavior, this method must be redefined. However,
# there are other ways of setting the +cache_key+ a serializer uses.
def cache_key
attributes.fetch(:cache_key) { "#{self.class.name.downcase}/#{id}-#{updated_at.strftime('%Y%m%d%H%M%S%9N')}" }
ActiveSupport::Cache.expand_cache_key([
self.class.model_name.name.downcase,
"#{id}-#{updated_at.strftime('%Y%m%d%H%M%S%9N')}"
].compact)
end
# Defaults to the time the serializer file was modified.
# When no set, defaults to the time the file was modified.
# See NOTE by attr_writer :updated_at
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
defined?(@updated_at) ? @updated_at : File.mtime(__FILE__)
end
# The following methods are needed to be minimally implemented for ActiveModel::Errors

View File

@ -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

View File

@ -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,19 +23,19 @@ 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',
author: @author, comments: [@comment1, @comment2],
publish_at: '2020-03-16T03:55:25.291Z')
@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
@comment2.post = @post
end
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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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'

View File

@ -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

View File

@ -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'

View File

@ -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}"

View File

@ -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'

View File

@ -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')
@ -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
@ -516,7 +532,7 @@ module ActiveModelSerializers
role_hash = role_serializer.fetch_attributes_fragment(adapter_instance)
assert_equal(role_hash, expected_result)
role.attributes[:id] = 'this has been updated'
role.id = 'this has been updated'
role.name = 'this was cached'
role_hash = role_serializer.fetch_attributes_fragment(adapter_instance)

View File

@ -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

View File

@ -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

306
test/fixtures/poro.rb vendored
View File

@ -1,25 +1,27 @@
verbose = $VERBOSE
$VERBOSE = nil
class Model < ActiveModelSerializers::Model
FILE_DIGEST = Digest::MD5.hexdigest(File.open(__FILE__).read)
### Helper methods, not required to be serializable
# Defaults to the downcased model name.
def id
@id ||= self.class.model_name.name.downcase
end
# 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
end
@ -30,67 +32,59 @@ end
# model = ModelWithErrors.new
# model.validate! # => ["cannot be nil"]
# model.errors.full_messages # => ["name cannot be nil"]
class ModelWithErrors < ::ActiveModelSerializers::Model
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}"
end
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 +96,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 +180,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
end
class PaginatedSerializer < ActiveModel::Serializer::CollectionSerializer
def json_key
'paginated'
module Spam
class UnrelatedLink < Model
end
class UnrelatedLinkSerializer < ActiveModel::Serializer
cache only: [:id]
attributes :id
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
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
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 +225,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

View File

@ -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 },

View File

@ -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 },

View File

@ -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

View File

@ -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