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

@ -3,42 +3,58 @@
# serializable non-activerecord objects. # serializable non-activerecord objects.
module ActiveModelSerializers module ActiveModelSerializers
class Model class Model
include ActiveModel::Model
include ActiveModel::Serializers::JSON 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) 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 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 = {}) def initialize(attributes = {})
@attributes = attributes && attributes.symbolize_keys
@errors = ActiveModel::Errors.new(self) @errors = ActiveModel::Errors.new(self)
super super
end end
# Defaults to the downcased model name. # The the fields in +attribute_names+ determines the returned hash.
def id # +attributes+ are returned frozen to prevent any expectations that mutation affects
attributes.fetch(:id) { self.class.name.downcase } # 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 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 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 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 def updated_at
attributes.fetch(:updated_at) { File.mtime(__FILE__) } defined?(@updated_at) ? @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
# The following methods are needed to be minimally implemented for ActiveModel::Errors # The following methods are needed to be minimally implemented for ActiveModel::Errors

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

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

@ -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')
@ -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
@ -516,7 +532,7 @@ module ActiveModelSerializers
role_hash = role_serializer.fetch_attributes_fragment(adapter_instance) role_hash = role_serializer.fetch_attributes_fragment(adapter_instance)
assert_equal(role_hash, expected_result) 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.name = 'this was cached'
role_hash = role_serializer.fetch_attributes_fragment(adapter_instance) role_hash = role_serializer.fetch_attributes_fragment(adapter_instance)

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

306
test/fixtures/poro.rb vendored
View File

@ -1,25 +1,27 @@
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 # Defaults to the downcased model name.
def id
@id ||= self.class.model_name.name.downcase
end
# 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 end
end end
@ -30,67 +32,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
attributes :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 +96,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 +180,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 +225,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

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