diff --git a/CHANGELOG.md b/CHANGELOG.md index 66289ace..f8574b9a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,8 +10,12 @@ Features: Fixes: +- [#1984](https://github.com/rails-api/active_model_serializers/pull/1984) Mutation of ActiveModelSerializers::Model now changes the attributes. (@bf4) + Misc: +- [#1984](https://github.com/rails-api/active_model_serializers/pull/1984) Make test attributes explicit. Test models have 'associations' support. (@bf4) + ### [v0.10.3 (2016-11-21)](https://github.com/rails-api/active_model_serializers/compare/v0.10.2...v0.10.3) Fixes: diff --git a/lib/active_model_serializers.rb b/lib/active_model_serializers.rb index b55dae35..18cdd9f7 100644 --- a/lib/active_model_serializers.rb +++ b/lib/active_model_serializers.rb @@ -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' diff --git a/lib/active_model_serializers/model.rb b/lib/active_model_serializers/model.rb index 2abe3334..0bdeda21 100644 --- a/lib/active_model_serializers/model.rb +++ b/lib/active_model_serializers/model.rb @@ -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 attributes :updated_at which will redefine the methods + # or attribute_names << :updated_at. + 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 diff --git a/test/action_controller/adapter_selector_test.rb b/test/action_controller/adapter_selector_test.rb index 2746943f..6f22aae2 100644 --- a/test/action_controller/adapter_selector_test.rb +++ b/test/action_controller/adapter_selector_test.rb @@ -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 diff --git a/test/action_controller/json_api/fields_test.rb b/test/action_controller/json_api/fields_test.rb index 4bf08c7e..af87ad39 100644 --- a/test/action_controller/json_api/fields_test.rb +++ b/test/action_controller/json_api/fields_test.rb @@ -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 diff --git a/test/action_controller/json_api/transform_test.rb b/test/action_controller/json_api/transform_test.rb index 492b606b..69212f32 100644 --- a/test/action_controller/json_api/transform_test.rb +++ b/test/action_controller/json_api/transform_test.rb @@ -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 diff --git a/test/action_controller/namespace_lookup_test.rb b/test/action_controller/namespace_lookup_test.rb index 3203fd0b..f40cca11 100644 --- a/test/action_controller/namespace_lookup_test.rb +++ b/test/action_controller/namespace_lookup_test.rb @@ -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 diff --git a/test/action_controller/serialization_test.rb b/test/action_controller/serialization_test.rb index b5900e1d..e650cbfd 100644 --- a/test/action_controller/serialization_test.rb +++ b/test/action_controller/serialization_test.rb @@ -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 diff --git a/test/active_model_serializers/model_test.rb b/test/active_model_serializers/model_test.rb index abebb1d2..c2f31647 100644 --- a/test/active_model_serializers/model_test.rb +++ b/test/active_model_serializers/model_test.rb @@ -4,7 +4,7 @@ module ActiveModelSerializers class ModelTest < ActiveSupport::TestCase include ActiveModel::Serializer::Lint::Tests - def setup + setup do @resource = ActiveModelSerializers::Model.new end @@ -18,5 +18,52 @@ 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 } + instance = klass.new(original_attributes) + + # Initial value + expected_attributes = { id: nil, 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) + + # Change via accessor + instance.one = :not_one + + expected_attributes = { id: nil, one: :not_one, two: 2, three: 3 }.with_indifferent_access + assert_equal expected_attributes, instance.attributes + assert_equal :not_one, instance.one + assert_equal :not_one, 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 } + instance = klass.new(original_attributes) + + # Initial value + expected_attributes = { id: :ego, 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) + + # Change via accessor + instance.id = :superego + + expected_attributes = { id: :superego, one: 1, two: 2, three: 3 }.with_indifferent_access + assert_equal expected_attributes, instance.attributes + assert_equal :superego, instance.id + assert_equal :superego, instance.read_attribute_for_serialization(:id) + ensure + self.class.send(:remove_const, :SomeTestModel) + end end end diff --git a/test/adapter/json_api/fields_test.rb b/test/adapter/json_api/fields_test.rb index 8aea4a1d..85228318 100644 --- a/test/adapter/json_api/fields_test.rb +++ b/test/adapter/json_api/fields_test.rb @@ -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' diff --git a/test/adapter/json_api/include_data_if_sideloaded_test.rb b/test/adapter/json_api/include_data_if_sideloaded_test.rb index 1c97191d..728eae13 100644 --- a/test/adapter/json_api/include_data_if_sideloaded_test.rb +++ b/test/adapter/json_api/include_data_if_sideloaded_test.rb @@ -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 diff --git a/test/adapter/json_api/linked_test.rb b/test/adapter/json_api/linked_test.rb index 949bcf60..0d9c69b6 100644 --- a/test/adapter/json_api/linked_test.rb +++ b/test/adapter/json_api/linked_test.rb @@ -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' diff --git a/test/adapter/json_api/links_test.rb b/test/adapter/json_api/links_test.rb index 3534b03c..ffbfa303 100644 --- a/test/adapter/json_api/links_test.rb +++ b/test/adapter/json_api/links_test.rb @@ -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}" diff --git a/test/adapter/json_api/transform_test.rb b/test/adapter/json_api/transform_test.rb index 47488d29..887ec835 100644 --- a/test/adapter/json_api/transform_test.rb +++ b/test/adapter/json_api/transform_test.rb @@ -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' diff --git a/test/cache_test.rb b/test/cache_test.rb index 44527378..b2cb27eb 100644 --- a/test/cache_test.rb +++ b/test/cache_test.rb @@ -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) diff --git a/test/collection_serializer_test.rb b/test/collection_serializer_test.rb index 7b2a33d2..cdbebb15 100644 --- a/test/collection_serializer_test.rb +++ b/test/collection_serializer_test.rb @@ -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 diff --git a/test/fixtures/active_record.rb b/test/fixtures/active_record.rb index 77ac030d..9dc3830d 100644 --- a/test/fixtures/active_record.rb +++ b/test/fixtures/active_record.rb @@ -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 diff --git a/test/fixtures/poro.rb b/test/fixtures/poro.rb index b7b82dff..3c804ccc 100644 --- a/test/fixtures/poro.rb +++ b/test/fixtures/poro.rb @@ -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 diff --git a/test/serializers/associations_test.rb b/test/serializers/associations_test.rb index ee470385..6d6447c3 100644 --- a/test/serializers/associations_test.rb +++ b/test/serializers/associations_test.rb @@ -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 }, diff --git a/test/serializers/attribute_test.rb b/test/serializers/attribute_test.rb index c359d2f9..608898c3 100644 --- a/test/serializers/attribute_test.rb +++ b/test/serializers/attribute_test.rb @@ -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 }, diff --git a/test/serializers/options_test.rb b/test/serializers/options_test.rb index 092714ab..009388e3 100644 --- a/test/serializers/options_test.rb +++ b/test/serializers/options_test.rb @@ -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 diff --git a/test/serializers/serializer_for_with_namespace_test.rb b/test/serializers/serializer_for_with_namespace_test.rb index 5a8a9ed5..5c6e3e5e 100644 --- a/test/serializers/serializer_for_with_namespace_test.rb +++ b/test/serializers/serializer_for_with_namespace_test.rb @@ -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