Merge pull request #1815 from dubadub/making-rubocop-happy

Fix code-styling issues from .rubocop_todo.yml

* re: RuboCop: Bulk minor style corrections

* re: RuboCop - hash indention corrections

* re: RuboCop - replace rocket style hashes

* re: RuboCop - get rid of redundant curly braces around a hash parameter

* re: RuboCop - Align the elements of a hash literal if they span more than one line.

* re: RuboCop - Use nested module/class definition instead of compact style.

* re: RuboCop - Suppress of handling LoadError for optional dependencies

* re: RuboCop - use include_ prefix instead of has_

* re: RuboCop - Disable Style/PredicateName rule for public API methods

* re: RuboCop - Remove empty .rubocop_todo.yml

* re: RuboCop - replace rocket style hashes
This commit is contained in:
Benjamin Fleischer 2016-06-26 22:22:55 -05:00 committed by GitHub
commit f4e00dc65d
55 changed files with 1067 additions and 1208 deletions

View File

@ -1,7 +1,5 @@
inherit_from: .rubocop_todo.yml
AllCops: AllCops:
TargetRubyVersion: 2.2 TargetRubyVersion: 2.1
Exclude: Exclude:
- config/initializers/forbidden_yaml.rb - config/initializers/forbidden_yaml.rb
- !ruby/regexp /(vendor|bundle|bin|db|tmp)\/.*/ - !ruby/regexp /(vendor|bundle|bin|db|tmp)\/.*/
@ -46,7 +44,7 @@ Style/AlignParameters:
EnforcedStyle: with_fixed_indentation EnforcedStyle: with_fixed_indentation
Style/ClassAndModuleChildren: Style/ClassAndModuleChildren:
EnforcedStyle: compact EnforcedStyle: nested
Style/Documentation: Style/Documentation:
Enabled: false Enabled: false

View File

@ -1,167 +0,0 @@
# This configuration was generated by
# `rubocop --auto-gen-config`
# on 2016-03-08 22:29:52 +0100 using RuboCop version 0.37.2.
# The point is for the user to remove these configuration records
# one by one as the offenses are removed from the code base.
# Note that changes in the inspected code, or installation of new
# versions of RuboCop, may require this file to be generated again.
# Offense count: 2
Lint/HandleExceptions:
Exclude:
- 'Rakefile'
# Offense count: 2
# Cop supports --auto-correct.
# Configuration parameters: AllowUnusedKeywordArguments, IgnoreEmptyMethods.
Lint/UnusedMethodArgument:
Exclude:
- 'test/lint_test.rb'
# Offense count: 4
# Configuration parameters: EnforcedStyle, SupportedStyles.
# SupportedStyles: strict, flexible
Rails/TimeZone:
Exclude:
- 'test/action_controller/serialization_test.rb'
- 'test/serializers/cache_test.rb'
# Offense count: 16
# Cop supports --auto-correct.
# Configuration parameters: EnforcedHashRocketStyle, EnforcedColonStyle, EnforcedLastArgumentHashStyle, SupportedLastArgumentHashStyles.
# SupportedLastArgumentHashStyles: always_inspect, always_ignore, ignore_implicit, ignore_explicit
Style/AlignHash:
Exclude:
- 'test/action_controller/json_api/pagination_test.rb'
# Offense count: 27
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles.
# SupportedStyles: braces, no_braces, context_dependent
Style/BracesAroundHashParameters:
Exclude:
- 'test/action_controller/adapter_selector_test.rb'
- 'test/action_controller/json_api/pagination_test.rb'
- 'test/adapter/json_api/linked_test.rb'
- 'test/adapter/json_api/pagination_links_test.rb'
- 'test/adapter/null_test.rb'
- 'test/adapter_test.rb'
- 'test/collection_serializer_test.rb'
- 'test/serializable_resource_test.rb'
- 'test/serializers/associations_test.rb'
- 'test/serializers/attributes_test.rb'
- 'test/serializers/root_test.rb'
# Offense count: 271
# Configuration parameters: EnforcedStyle, SupportedStyles.
# SupportedStyles: nested, compact
Style/ClassAndModuleChildren:
Enabled: false
# Offense count: 6
# Cop supports --auto-correct.
Style/CommentIndentation:
Exclude:
- 'active_model_serializers.gemspec'
# Offense count: 1
Style/DoubleNegation:
Exclude:
- 'lib/active_model/serializable_resource.rb'
# Offense count: 1
# Configuration parameters: MinBodyLength.
Style/GuardClause:
Exclude:
- 'lib/active_model/serializer.rb'
# Offense count: 58
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles, UseHashRocketsWithSymbolValues.
# SupportedStyles: ruby19, ruby19_no_mixed_keys, hash_rockets
Style/HashSyntax:
Enabled: false
# Offense count: 4
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles, IndentationWidth.
# SupportedStyles: special_inside_parentheses, consistent, align_brackets
Style/IndentArray:
Enabled: false
# Offense count: 10
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles, IndentationWidth.
# SupportedStyles: special_inside_parentheses, consistent, align_braces
Style/IndentHash:
Enabled: false
# Offense count: 1
# Cop supports --auto-correct.
Style/Lambda:
Exclude:
- 'lib/active_model/serializer.rb'
# Offense count: 1
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles.
# SupportedStyles: require_parentheses, require_no_parentheses, require_no_parentheses_except_multiline
Style/MethodDefParentheses:
Enabled: false
# Offense count: 1
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles, IndentationWidth.
# SupportedStyles: aligned, indented
Style/MultilineOperationIndentation:
Enabled: false
# Offense count: 1
# Cop supports --auto-correct.
Style/NegatedIf:
Exclude:
- 'lib/action_controller/serialization.rb'
# Offense count: 1
# Cop supports --auto-correct.
Style/PerlBackrefs:
Exclude:
- 'test/fixtures/poro.rb'
# Offense count: 3
# Configuration parameters: NamePrefix, NamePrefixBlacklist, NameWhitelist.
# NamePrefix: is_, has_, have_
# NamePrefixBlacklist: is_, has_, have_
# NameWhitelist: is_a?
Style/PredicateName:
Exclude:
- 'lib/active_model/serializer/associations.rb'
- 'test/action_controller/json_api/linked_test.rb'
# Offense count: 1
# Cop supports --auto-correct.
Style/RedundantSelf:
Exclude:
- 'test/fixtures/poro.rb'
# Offense count: 1
# Cop supports --auto-correct.
# Configuration parameters: AllowIfMethodIsEmpty.
Style/SingleLineMethods:
Exclude:
- 'test/serializers/serializer_for_test.rb'
# Offense count: 4
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles.
# SupportedStyles: single_quotes, double_quotes
Style/StringLiteralsInInterpolation:
Enabled: false
# Offense count: 1
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles.
# SupportedStyles: final_newline, final_blank_line
Style/TrailingBlankLines:
Exclude:
- 'test/adapter/null_test.rb'

View File

@ -5,7 +5,7 @@ rescue LoadError
end end
begin begin
require 'simplecov' require 'simplecov'
rescue LoadError rescue LoadError # rubocop:disable Lint/HandleExceptions
end end
Bundler::GemHelper.install_tasks Bundler::GemHelper.install_tasks
@ -33,7 +33,7 @@ end
begin begin
require 'rubocop' require 'rubocop'
require 'rubocop/rake_task' require 'rubocop/rake_task'
rescue LoadError rescue LoadError # rubocop:disable Lint/HandleExceptions
else else
Rake::Task[:rubocop].clear if Rake::Task.task_defined?(:rubocop) Rake::Task[:rubocop].clear if Rake::Task.task_defined?(:rubocop)
require 'rbconfig' require 'rbconfig'
@ -100,4 +100,4 @@ else
end end
desc 'CI test task' desc 'CI test task'
task :ci => [:default] task ci: [:default]

View File

@ -23,31 +23,31 @@ Gem::Specification.new do |spec|
rails_versions = ['>= 4.1', '< 6'] rails_versions = ['>= 4.1', '< 6']
spec.add_runtime_dependency 'activemodel', rails_versions spec.add_runtime_dependency 'activemodel', rails_versions
# 'activesupport', rails_versions # 'activesupport', rails_versions
# 'builder' # 'builder'
spec.add_runtime_dependency 'actionpack', rails_versions spec.add_runtime_dependency 'actionpack', rails_versions
# 'activesupport', rails_versions # 'activesupport', rails_versions
# 'rack' # 'rack'
# 'rack-test', '~> 0.6.2' # 'rack-test', '~> 0.6.2'
spec.add_runtime_dependency 'railties', rails_versions spec.add_runtime_dependency 'railties', rails_versions
# 'activesupport', rails_versions # 'activesupport', rails_versions
# 'actionpack', rails_versions # 'actionpack', rails_versions
# 'rake', '>= 0.8.7' # 'rake', '>= 0.8.7'
# 'activesupport', rails_versions # 'activesupport', rails_versions
# 'i18n, # 'i18n,
# 'tzinfo' # 'tzinfo'
# 'minitest' # 'minitest'
# 'thread_safe' # 'thread_safe'
spec.add_runtime_dependency 'jsonapi', '~> 0.1.1.beta2' spec.add_runtime_dependency 'jsonapi', '~> 0.1.1.beta2'
spec.add_development_dependency 'activerecord', rails_versions spec.add_development_dependency 'activerecord', rails_versions
# arel # arel
# activesupport # activesupport
# activemodel # activemodel
# Soft dependency for pagination # Soft dependency for pagination
spec.add_development_dependency 'kaminari', ' ~> 0.16.3' spec.add_development_dependency 'kaminari', ' ~> 0.16.3'

View File

@ -19,12 +19,13 @@ module ActionController
end end
def serialization_scope def serialization_scope
send(_serialization_scope) if _serialization_scope && return unless _serialization_scope && respond_to?(_serialization_scope, true)
respond_to?(_serialization_scope, true)
send(_serialization_scope)
end end
def get_serializer(resource, options = {}) def get_serializer(resource, options = {})
if !use_adapter? unless use_adapter?
warn 'ActionController::Serialization#use_adapter? has been removed. '\ warn 'ActionController::Serialization#use_adapter? has been removed. '\
"Please pass 'adapter: false' or see ActiveSupport::SerializableResource.new" "Please pass 'adapter: false' or see ActiveSupport::SerializableResource.new"
options[:adapter] = false options[:adapter] = false

View File

@ -125,10 +125,9 @@ module ActiveModel
self.root = instance_options[:root] self.root = instance_options[:root]
self.scope = instance_options[:scope] self.scope = instance_options[:scope]
scope_name = instance_options[:scope_name] return if !(scope_name = instance_options[:scope_name]) || respond_to?(scope_name)
if scope_name && !respond_to?(scope_name)
define_singleton_method scope_name, lambda { scope } define_singleton_method scope_name, -> { scope }
end
end end
def success? def success?

View File

@ -1,9 +1,12 @@
require 'active_model/serializer/collection_serializer' require 'active_model/serializer/collection_serializer'
class ActiveModel::Serializer
class ArraySerializer < CollectionSerializer module ActiveModel
class << self class Serializer
extend ActiveModelSerializers::Deprecate class ArraySerializer < CollectionSerializer
deprecate :new, 'ActiveModel::Serializer::CollectionSerializer.' class << self
extend ActiveModelSerializers::Deprecate
deprecate :new, 'ActiveModel::Serializer::CollectionSerializer.'
end
end end
end end
end end

View File

@ -39,7 +39,7 @@ module ActiveModel
# @example # @example
# has_many :comments, serializer: CommentSummarySerializer # has_many :comments, serializer: CommentSummarySerializer
# #
def has_many(name, options = {}, &block) def has_many(name, options = {}, &block) # rubocop:disable Style/PredicateName
associate(HasManyReflection.new(name, options, block)) associate(HasManyReflection.new(name, options, block))
end end
@ -61,7 +61,7 @@ module ActiveModel
# @example # @example
# has_one :author, serializer: AuthorSerializer # has_one :author, serializer: AuthorSerializer
# #
def has_one(name, options = {}, &block) def has_one(name, options = {}, &block) # rubocop:disable Style/PredicateName
associate(HasOneReflection.new(name, options, block)) associate(HasOneReflection.new(name, options, block))
end end

View File

@ -1,10 +1,14 @@
class ActiveModel::Serializer::ErrorSerializer < ActiveModel::Serializer module ActiveModel
# @return [Hash<field_name,Array<error_message>>] class Serializer
def as_json class ErrorSerializer < ActiveModel::Serializer
object.errors.messages # @return [Hash<field_name,Array<error_message>>]
end def as_json
object.errors.messages
end
def success? def success?
false false
end
end
end end
end end

View File

@ -1,27 +1,32 @@
require 'active_model/serializer/error_serializer' require 'active_model/serializer/error_serializer'
class ActiveModel::Serializer::ErrorsSerializer
include Enumerable
delegate :each, to: :@serializers
attr_reader :object, :root
def initialize(resources, options = {}) module ActiveModel
@root = options[:root] class Serializer
@object = resources class ErrorsSerializer
@serializers = resources.map do |resource| include Enumerable
serializer_class = options.fetch(:serializer) { ActiveModel::Serializer::ErrorSerializer } delegate :each, to: :@serializers
serializer_class.new(resource, options.except(:serializer)) attr_reader :object, :root
def initialize(resources, options = {})
@root = options[:root]
@object = resources
@serializers = resources.map do |resource|
serializer_class = options.fetch(:serializer) { ActiveModel::Serializer::ErrorSerializer }
serializer_class.new(resource, options.except(:serializer))
end
end
def success?
false
end
def json_key
nil
end
protected
attr_reader :serializers
end end
end end
def success?
false
end
def json_key
nil
end
protected
attr_reader :serializers
end end

View File

@ -1,146 +1,150 @@
module ActiveModel::Serializer::Lint module ActiveModel
# == Active \Model \Serializer \Lint \Tests class Serializer
# module Lint
# You can test whether an object is compliant with the Active \Model \Serializers # == Active \Model \Serializer \Lint \Tests
# API by including <tt>ActiveModel::Serializer::Lint::Tests</tt> in your TestCase. #
# It will include tests that tell you whether your object is fully compliant, # You can test whether an object is compliant with the Active \Model \Serializers
# or if not, which aspects of the API are not implemented. # API by including <tt>ActiveModel::Serializer::Lint::Tests</tt> in your TestCase.
# # It will include tests that tell you whether your object is fully compliant,
# Note an object is not required to implement all APIs in order to work # or if not, which aspects of the API are not implemented.
# with Active \Model \Serializers. This module only intends to provide guidance in case #
# you want all features out of the box. # Note an object is not required to implement all APIs in order to work
# # with Active \Model \Serializers. This module only intends to provide guidance in case
# These tests do not attempt to determine the semantic correctness of the # you want all features out of the box.
# returned values. For instance, you could implement <tt>serializable_hash</tt> to #
# always return +{}+, and the tests would pass. It is up to you to ensure # These tests do not attempt to determine the semantic correctness of the
# that the values are semantically meaningful. # returned values. For instance, you could implement <tt>serializable_hash</tt> to
module Tests # always return +{}+, and the tests would pass. It is up to you to ensure
# Passes if the object responds to <tt>serializable_hash</tt> and if it takes # that the values are semantically meaningful.
# zero or one arguments. module Tests
# Fails otherwise. # Passes if the object responds to <tt>serializable_hash</tt> and if it takes
# # zero or one arguments.
# <tt>serializable_hash</tt> returns a hash representation of a object's attributes. # Fails otherwise.
# Typically, it is implemented by including ActiveModel::Serialization. #
def test_serializable_hash # <tt>serializable_hash</tt> returns a hash representation of a object's attributes.
assert_respond_to resource, :serializable_hash, 'The resource should respond to serializable_hash' # Typically, it is implemented by including ActiveModel::Serialization.
resource.serializable_hash def test_serializable_hash
resource.serializable_hash(nil) assert_respond_to resource, :serializable_hash, 'The resource should respond to serializable_hash'
end resource.serializable_hash
resource.serializable_hash(nil)
end
# Passes if the object responds to <tt>read_attribute_for_serialization</tt> # Passes if the object responds to <tt>read_attribute_for_serialization</tt>
# and if it requires one argument (the attribute to be read). # and if it requires one argument (the attribute to be read).
# Fails otherwise. # Fails otherwise.
# #
# <tt>read_attribute_for_serialization</tt> gets the attribute value for serialization # <tt>read_attribute_for_serialization</tt> gets the attribute value for serialization
# Typically, it is implemented by including ActiveModel::Serialization. # Typically, it is implemented by including ActiveModel::Serialization.
def test_read_attribute_for_serialization def test_read_attribute_for_serialization
assert_respond_to resource, :read_attribute_for_serialization, 'The resource should respond to read_attribute_for_serialization' assert_respond_to resource, :read_attribute_for_serialization, 'The resource should respond to read_attribute_for_serialization'
actual_arity = resource.method(:read_attribute_for_serialization).arity actual_arity = resource.method(:read_attribute_for_serialization).arity
# using absolute value since arity is: # using absolute value since arity is:
# 1 for def read_attribute_for_serialization(name); end # 1 for def read_attribute_for_serialization(name); end
# -1 for alias :read_attribute_for_serialization :send # -1 for alias :read_attribute_for_serialization :send
assert_equal 1, actual_arity.abs, "expected #{actual_arity.inspect}.abs to be 1 or -1" assert_equal 1, actual_arity.abs, "expected #{actual_arity.inspect}.abs to be 1 or -1"
end end
# Passes if the object responds to <tt>as_json</tt> and if it takes # Passes if the object responds to <tt>as_json</tt> and if it takes
# zero or one arguments. # zero or one arguments.
# Fails otherwise. # Fails otherwise.
# #
# <tt>as_json</tt> returns a hash representation of a serialized object. # <tt>as_json</tt> returns a hash representation of a serialized object.
# It may delegate to <tt>serializable_hash</tt> # It may delegate to <tt>serializable_hash</tt>
# Typically, it is implemented either by including ActiveModel::Serialization # Typically, it is implemented either by including ActiveModel::Serialization
# which includes ActiveModel::Serializers::JSON. # which includes ActiveModel::Serializers::JSON.
# or by the JSON gem when required. # or by the JSON gem when required.
def test_as_json def test_as_json
assert_respond_to resource, :as_json assert_respond_to resource, :as_json
resource.as_json resource.as_json
resource.as_json(nil) resource.as_json(nil)
end end
# Passes if the object responds to <tt>to_json</tt> and if it takes # Passes if the object responds to <tt>to_json</tt> and if it takes
# zero or one arguments. # zero or one arguments.
# Fails otherwise. # Fails otherwise.
# #
# <tt>to_json</tt> returns a string representation (JSON) of a serialized object. # <tt>to_json</tt> returns a string representation (JSON) of a serialized object.
# It may be called on the result of <tt>as_json</tt>. # It may be called on the result of <tt>as_json</tt>.
# Typically, it is implemented on all objects when the JSON gem is required. # Typically, it is implemented on all objects when the JSON gem is required.
def test_to_json def test_to_json
assert_respond_to resource, :to_json assert_respond_to resource, :to_json
resource.to_json resource.to_json
resource.to_json(nil) resource.to_json(nil)
end end
# Passes if the object responds to <tt>cache_key</tt> # Passes if the object responds to <tt>cache_key</tt>
# Fails otherwise. # Fails otherwise.
# #
# <tt>cache_key</tt> returns a (self-expiring) unique key for the object, # <tt>cache_key</tt> returns a (self-expiring) unique key for the object,
# and is part of the (self-expiring) cache_key, which is used by the # and is part of the (self-expiring) cache_key, which is used by the
# adapter. It is not required unless caching is enabled. # adapter. It is not required unless caching is enabled.
def test_cache_key def test_cache_key
assert_respond_to resource, :cache_key assert_respond_to resource, :cache_key
actual_arity = resource.method(:cache_key).arity actual_arity = resource.method(:cache_key).arity
assert_includes [-1, 0], actual_arity, "expected #{actual_arity.inspect} to be 0 or -1" assert_includes [-1, 0], actual_arity, "expected #{actual_arity.inspect} to be 0 or -1"
end end
# Passes if the object responds to <tt>updated_at</tt> and if it takes no # Passes if the object responds to <tt>updated_at</tt> and if it takes no
# arguments. # arguments.
# Fails otherwise. # Fails otherwise.
# #
# <tt>updated_at</tt> returns a Time object or iso8601 string and # <tt>updated_at</tt> returns a Time object or iso8601 string and
# is part of the (self-expiring) cache_key, which is used by the adapter. # is part of the (self-expiring) cache_key, which is used by the adapter.
# It is not required unless caching is enabled. # It is not required unless caching is enabled.
def test_updated_at def test_updated_at
assert_respond_to resource, :updated_at assert_respond_to resource, :updated_at
actual_arity = resource.method(:updated_at).arity actual_arity = resource.method(:updated_at).arity
assert_equal 0, actual_arity assert_equal 0, actual_arity
end end
# Passes if the object responds to <tt>id</tt> and if it takes no # Passes if the object responds to <tt>id</tt> and if it takes no
# arguments. # arguments.
# Fails otherwise. # Fails otherwise.
# #
# <tt>id</tt> returns a unique identifier for the object. # <tt>id</tt> returns a unique identifier for the object.
# It is not required unless caching is enabled. # It is not required unless caching is enabled.
def test_id def test_id
assert_respond_to resource, :id assert_respond_to resource, :id
assert_equal 0, resource.method(:id).arity assert_equal 0, resource.method(:id).arity
end end
# Passes if the object's class responds to <tt>model_name</tt> and if it # Passes if the object's class responds to <tt>model_name</tt> and if it
# is in an instance of +ActiveModel::Name+. # is in an instance of +ActiveModel::Name+.
# Fails otherwise. # Fails otherwise.
# #
# <tt>model_name</tt> returns an ActiveModel::Name instance. # <tt>model_name</tt> returns an ActiveModel::Name instance.
# It is used by the serializer to identify the object's type. # It is used by the serializer to identify the object's type.
# It is not required unless caching is enabled. # It is not required unless caching is enabled.
def test_model_name def test_model_name
resource_class = resource.class resource_class = resource.class
assert_respond_to resource_class, :model_name assert_respond_to resource_class, :model_name
assert_instance_of resource_class.model_name, ActiveModel::Name assert_instance_of resource_class.model_name, ActiveModel::Name
end end
def test_active_model_errors def test_active_model_errors
assert_respond_to resource, :errors assert_respond_to resource, :errors
end end
def test_active_model_errors_human_attribute_name def test_active_model_errors_human_attribute_name
assert_respond_to resource.class, :human_attribute_name assert_respond_to resource.class, :human_attribute_name
assert_equal(-2, resource.class.method(:human_attribute_name).arity) assert_equal(-2, resource.class.method(:human_attribute_name).arity)
end end
def test_active_model_errors_lookup_ancestors def test_active_model_errors_lookup_ancestors
assert_respond_to resource.class, :lookup_ancestors assert_respond_to resource.class, :lookup_ancestors
assert_equal 0, resource.class.method(:lookup_ancestors).arity assert_equal 0, resource.class.method(:lookup_ancestors).arity
end end
private private
def resource def resource
@resource or fail "'@resource' must be set as the linted object" @resource or fail "'@resource' must be set as the linted object"
end end
def assert_instance_of(result, name) def assert_instance_of(result, name)
assert result.instance_of?(name), "#{result} should be an instance of #{name}" assert result.instance_of?(name), "#{result} should be an instance of #{name}"
end
end
end end
end end
end end

View File

@ -36,7 +36,7 @@ module ActiveModelSerializers
target = is_a?(Module) ? "#{self}." : "#{self.class}#" target = is_a?(Module) ? "#{self}." : "#{self.class}#"
msg = ["NOTE: #{target}#{name} is deprecated", msg = ["NOTE: #{target}#{name} is deprecated",
replacement == :none ? ' with no replacement' : "; use #{replacement} instead", replacement == :none ? ' with no replacement' : "; use #{replacement} instead",
"\n#{target}#{name} called from #{ActiveModelSerializers.location_of_caller.join(":")}"] "\n#{target}#{name} called from #{ActiveModelSerializers.location_of_caller.join(':')}"]
warn "#{msg.join}." warn "#{msg.join}."
send old, *args, &block send old, *args, &block
end end

View File

@ -21,7 +21,7 @@ module ActiveModelSerializers
# Defaults to the downcased model name and updated_at # Defaults to the downcased model name and updated_at
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")}" } attributes.fetch(:cache_key) { "#{self.class.name.downcase}/#{id}-#{updated_at.strftime('%Y%m%d%H%M%S%9N')}" }
end end
# Defaults to the time the serializer file was modified. # Defaults to the time the serializer file was modified.

View File

@ -23,7 +23,7 @@ module ActiveModelSerializers
# This hook is run after the action_controller railtie has set the configuration # This hook is run after the action_controller railtie has set the configuration
# based on the *environment* configuration and before any config/initializers are run # based on the *environment* configuration and before any config/initializers are run
# and also before eager_loading (if enabled). # and also before eager_loading (if enabled).
initializer 'active_model_serializers.set_configs', :after => 'action_controller.set_configs' do initializer 'active_model_serializers.set_configs', after: 'action_controller.set_configs' do
ActiveModelSerializers.logger = Rails.configuration.action_controller.logger ActiveModelSerializers.logger = Rails.configuration.action_controller.logger
ActiveModelSerializers.config.perform_caching = Rails.configuration.action_controller.perform_caching ActiveModelSerializers.config.perform_caching = Rails.configuration.action_controller.perform_caching
# We want this hook to run after the config has been set, even if ActionController has already loaded. # We want this hook to run after the config has been set, even if ActionController has already loaded.

View File

@ -22,49 +22,51 @@
# render jsonapi: model # render jsonapi: model
# #
# No wrapper format needed as it does not apply (i.e. no `wrap_parameters format: [jsonapi]`) # No wrapper format needed as it does not apply (i.e. no `wrap_parameters format: [jsonapi]`)
module ActiveModelSerializers::Jsonapi module ActiveModelSerializers
MEDIA_TYPE = 'application/vnd.api+json'.freeze module Jsonapi
HEADERS = { MEDIA_TYPE = 'application/vnd.api+json'.freeze
response: { 'CONTENT_TYPE'.freeze => MEDIA_TYPE }, HEADERS = {
request: { 'ACCEPT'.freeze => MEDIA_TYPE } response: { 'CONTENT_TYPE'.freeze => MEDIA_TYPE },
}.freeze request: { 'ACCEPT'.freeze => MEDIA_TYPE }
}.freeze
def self.install def self.install
# actionpack/lib/action_dispatch/http/mime_types.rb # actionpack/lib/action_dispatch/http/mime_types.rb
Mime::Type.register MEDIA_TYPE, :jsonapi Mime::Type.register MEDIA_TYPE, :jsonapi
if Rails::VERSION::MAJOR >= 5 if Rails::VERSION::MAJOR >= 5
ActionDispatch::Request.parameter_parsers[:jsonapi] = parser ActionDispatch::Request.parameter_parsers[:jsonapi] = parser
else else
ActionDispatch::ParamsParser::DEFAULT_PARSERS[Mime[:jsonapi]] = parser ActionDispatch::ParamsParser::DEFAULT_PARSERS[Mime[:jsonapi]] = parser
end end
# ref https://github.com/rails/rails/pull/21496 # ref https://github.com/rails/rails/pull/21496
ActionController::Renderers.add :jsonapi do |json, options| ActionController::Renderers.add :jsonapi do |json, options|
json = serialize_jsonapi(json, options).to_json(options) unless json.is_a?(String) json = serialize_jsonapi(json, options).to_json(options) unless json.is_a?(String)
self.content_type ||= Mime[:jsonapi] self.content_type ||= Mime[:jsonapi]
self.response_body = json self.response_body = json
end end
end end
# Proposal: should actually deserialize the JSON API params # Proposal: should actually deserialize the JSON API params
# to the hash format expected by `ActiveModel::Serializers::JSON` # to the hash format expected by `ActiveModel::Serializers::JSON`
# actionpack/lib/action_dispatch/http/parameters.rb # actionpack/lib/action_dispatch/http/parameters.rb
def self.parser def self.parser
lambda do |body| lambda do |body|
data = JSON.parse(body) data = JSON.parse(body)
data = { :_json => data } unless data.is_a?(Hash) data = { _json: data } unless data.is_a?(Hash)
data.with_indifferent_access data.with_indifferent_access
end end
end end
module ControllerSupport module ControllerSupport
def serialize_jsonapi(json, options) def serialize_jsonapi(json, options)
options[:adapter] = :json_api options[:adapter] = :json_api
options.fetch(:serialization_context) do options.fetch(:serialization_context) do
options[:serialization_context] = ActiveModelSerializers::SerializationContext.new(request) options[:serialization_context] = ActiveModelSerializers::SerializationContext.new(request)
end
get_serializer(json, options)
end end
get_serializer(json, options)
end end
end end
end end

View File

@ -2,11 +2,11 @@ module Rails
module Generators module Generators
class SerializerGenerator < NamedBase class SerializerGenerator < NamedBase
source_root File.expand_path('../templates', __FILE__) source_root File.expand_path('../templates', __FILE__)
check_class_collision :suffix => 'Serializer' check_class_collision suffix: 'Serializer'
argument :attributes, :type => :array, :default => [], :banner => 'field:type field:type' argument :attributes, type: :array, default: [], banner: 'field:type field:type'
class_option :parent, :type => :string, :desc => 'The parent class for the generated serializer' class_option :parent, type: :string, desc: 'The parent class for the generated serializer'
def create_serializer_file def create_serializer_file
template 'serializer.rb.erb', File.join('app/serializers', class_path, "#{file_name}_serializer.rb") template 'serializer.rb.erb', File.join('app/serializers', class_path, "#{file_name}_serializer.rb")

View File

@ -4,11 +4,13 @@ require 'active_model_serializers'
require 'grape/formatters/active_model_serializers' require 'grape/formatters/active_model_serializers'
require 'grape/helpers/active_model_serializers' require 'grape/helpers/active_model_serializers'
module Grape::ActiveModelSerializers module Grape
extend ActiveSupport::Concern module ActiveModelSerializers
extend ActiveSupport::Concern
included do included do
formatter :json, Grape::Formatters::ActiveModelSerializers formatter :json, Grape::Formatters::ActiveModelSerializers
helpers Grape::Helpers::ActiveModelSerializers helpers Grape::Helpers::ActiveModelSerializers
end
end end
end end

View File

@ -5,17 +5,17 @@ module ActionController
class AdapterSelectorTest < ActionController::TestCase class AdapterSelectorTest < ActionController::TestCase
class AdapterSelectorTestController < ActionController::Base class AdapterSelectorTestController < ActionController::Base
def render_using_default_adapter def render_using_default_adapter
@profile = Profile.new({ name: 'Name 1', description: 'Description 1', comments: 'Comments 1' }) @profile = Profile.new(name: 'Name 1', description: 'Description 1', comments: 'Comments 1')
render json: @profile render json: @profile
end end
def render_using_adapter_override def render_using_adapter_override
@profile = Profile.new({ name: 'Name 1', description: 'Description 1', comments: 'Comments 1' }) @profile = Profile.new(name: 'Name 1', description: 'Description 1', comments: 'Comments 1')
render json: @profile, adapter: :json_api render json: @profile, adapter: :json_api
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(name: 'Name 1', description: 'Description 1', comments: 'Comments 1')
render json: @profile, adapter: false render json: @profile, adapter: false
end end
end end

View File

@ -8,12 +8,11 @@ module ActionController
get :render_resource_with_errors get :render_resource_with_errors
expected_errors_object = { expected_errors_object = {
:errors => errors: [
[ { source: { pointer: '/data/attributes/name' }, detail: 'cannot be nil' },
{ :source => { :pointer => '/data/attributes/name' }, :detail => 'cannot be nil' }, { source: { pointer: '/data/attributes/name' }, detail: 'must be longer' },
{ :source => { :pointer => '/data/attributes/name' }, :detail => 'must be longer' }, { source: { pointer: '/data/attributes/id' }, detail: 'must be a uuid' }
{ :source => { :pointer => '/data/attributes/id' }, :detail => 'must be a uuid' } ]
]
}.to_json }.to_json
assert_equal json_reponse_body.to_json, expected_errors_object assert_equal json_reponse_body.to_json, expected_errors_object
end end

View File

@ -87,7 +87,7 @@ module ActionController
setup do setup do
@routes = Rails.application.routes.draw do @routes = Rails.application.routes.draw do
ActiveSupport::Deprecation.silence do ActiveSupport::Deprecation.silence do
match ':action', :to => LinkedTestController, via: [:get, :post] match ':action', to: LinkedTestController, via: [:get, :post]
end end
end end
end end
@ -183,17 +183,17 @@ module ActionController
get '/render_resource_with_missing_nested_has_many_include' get '/render_resource_with_missing_nested_has_many_include'
response = JSON.parse(@response.body) response = JSON.parse(@response.body)
assert response.key? 'included' assert response.key? 'included'
refute has_type?(response['included'], 'roles') refute include_type?(response['included'], 'roles')
end end
def test_render_collection_with_missing_nested_has_many_include def test_render_collection_with_missing_nested_has_many_include
get '/render_collection_with_missing_nested_has_many_include' get '/render_collection_with_missing_nested_has_many_include'
response = JSON.parse(@response.body) response = JSON.parse(@response.body)
assert response.key? 'included' assert response.key? 'included'
assert has_type?(response['included'], 'roles') assert include_type?(response['included'], 'roles')
end end
def has_type?(collection, value) def include_type?(collection, value)
collection.detect { |i| i['type'] == value } collection.detect { |i| i['type'] == value }
end end
end end

View File

@ -14,9 +14,9 @@ module ActionController
class PaginationTestController < ActionController::Base class PaginationTestController < ActionController::Base
def setup def setup
@array = [ @array = [
Profile.new({ name: 'Name 1', description: 'Description 1', comments: 'Comments 1' }), Profile.new(name: 'Name 1', description: 'Description 1', comments: 'Comments 1'),
Profile.new({ name: 'Name 2', description: 'Description 2', comments: 'Comments 2' }), Profile.new(name: 'Name 2', description: 'Description 2', comments: 'Comments 2'),
Profile.new({ name: 'Name 3', description: 'Description 3', comments: 'Comments 3' }) Profile.new(name: 'Name 3', description: 'Description 3', comments: 'Comments 3')
] ]
end end
@ -48,10 +48,10 @@ module ActionController
def test_render_pagination_links_with_will_paginate def test_render_pagination_links_with_will_paginate
expected_links = { 'self' => "#{WILL_PAGINATE_URI}?page%5Bnumber%5D=2&page%5Bsize%5D=1", expected_links = { 'self' => "#{WILL_PAGINATE_URI}?page%5Bnumber%5D=2&page%5Bsize%5D=1",
'first' => "#{WILL_PAGINATE_URI}?page%5Bnumber%5D=1&page%5Bsize%5D=1", 'first' => "#{WILL_PAGINATE_URI}?page%5Bnumber%5D=1&page%5Bsize%5D=1",
'prev' => "#{WILL_PAGINATE_URI}?page%5Bnumber%5D=1&page%5Bsize%5D=1", 'prev' => "#{WILL_PAGINATE_URI}?page%5Bnumber%5D=1&page%5Bsize%5D=1",
'next' => "#{WILL_PAGINATE_URI}?page%5Bnumber%5D=3&page%5Bsize%5D=1", 'next' => "#{WILL_PAGINATE_URI}?page%5Bnumber%5D=3&page%5Bsize%5D=1",
'last' => "#{WILL_PAGINATE_URI}?page%5Bnumber%5D=3&page%5Bsize%5D=1" } 'last' => "#{WILL_PAGINATE_URI}?page%5Bnumber%5D=3&page%5Bsize%5D=1" }
get :render_pagination_using_will_paginate, params: { page: { number: 2, size: 1 } } get :render_pagination_using_will_paginate, params: { page: { number: 2, size: 1 } }
response = JSON.parse(@response.body) response = JSON.parse(@response.body)
@ -60,8 +60,8 @@ module ActionController
def test_render_only_last_and_next_pagination_links def test_render_only_last_and_next_pagination_links
expected_links = { 'self' => "#{WILL_PAGINATE_URI}?page%5Bnumber%5D=1&page%5Bsize%5D=2", expected_links = { 'self' => "#{WILL_PAGINATE_URI}?page%5Bnumber%5D=1&page%5Bsize%5D=2",
'next' => "#{WILL_PAGINATE_URI}?page%5Bnumber%5D=2&page%5Bsize%5D=2", 'next' => "#{WILL_PAGINATE_URI}?page%5Bnumber%5D=2&page%5Bsize%5D=2",
'last' => "#{WILL_PAGINATE_URI}?page%5Bnumber%5D=2&page%5Bsize%5D=2" } 'last' => "#{WILL_PAGINATE_URI}?page%5Bnumber%5D=2&page%5Bsize%5D=2" }
get :render_pagination_using_will_paginate, params: { page: { number: 1, size: 2 } } get :render_pagination_using_will_paginate, params: { page: { number: 1, size: 2 } }
response = JSON.parse(@response.body) response = JSON.parse(@response.body)
assert_equal expected_links, response['links'] assert_equal expected_links, response['links']
@ -69,10 +69,10 @@ module ActionController
def test_render_pagination_links_with_kaminari def test_render_pagination_links_with_kaminari
expected_links = { 'self' => "#{KAMINARI_URI}?page%5Bnumber%5D=2&page%5Bsize%5D=1", expected_links = { 'self' => "#{KAMINARI_URI}?page%5Bnumber%5D=2&page%5Bsize%5D=1",
'first' => "#{KAMINARI_URI}?page%5Bnumber%5D=1&page%5Bsize%5D=1", 'first' => "#{KAMINARI_URI}?page%5Bnumber%5D=1&page%5Bsize%5D=1",
'prev' => "#{KAMINARI_URI}?page%5Bnumber%5D=1&page%5Bsize%5D=1", 'prev' => "#{KAMINARI_URI}?page%5Bnumber%5D=1&page%5Bsize%5D=1",
'next' => "#{KAMINARI_URI}?page%5Bnumber%5D=3&page%5Bsize%5D=1", 'next' => "#{KAMINARI_URI}?page%5Bnumber%5D=3&page%5Bsize%5D=1",
'last' => "#{KAMINARI_URI}?page%5Bnumber%5D=3&page%5Bsize%5D=1" } 'last' => "#{KAMINARI_URI}?page%5Bnumber%5D=3&page%5Bsize%5D=1" }
get :render_pagination_using_kaminari, params: { page: { number: 2, size: 1 } } get :render_pagination_using_kaminari, params: { page: { number: 2, size: 1 } }
response = JSON.parse(@response.body) response = JSON.parse(@response.body)
assert_equal expected_links, response['links'] assert_equal expected_links, response['links']
@ -80,8 +80,8 @@ module ActionController
def test_render_only_prev_and_first_pagination_links def test_render_only_prev_and_first_pagination_links
expected_links = { 'self' => "#{KAMINARI_URI}?page%5Bnumber%5D=3&page%5Bsize%5D=1", expected_links = { 'self' => "#{KAMINARI_URI}?page%5Bnumber%5D=3&page%5Bsize%5D=1",
'first' => "#{KAMINARI_URI}?page%5Bnumber%5D=1&page%5Bsize%5D=1", 'first' => "#{KAMINARI_URI}?page%5Bnumber%5D=1&page%5Bsize%5D=1",
'prev' => "#{KAMINARI_URI}?page%5Bnumber%5D=2&page%5Bsize%5D=1" } 'prev' => "#{KAMINARI_URI}?page%5Bnumber%5D=2&page%5Bsize%5D=1" }
get :render_pagination_using_kaminari, params: { page: { number: 3, size: 1 } } get :render_pagination_using_kaminari, params: { page: { number: 3, size: 1 } }
response = JSON.parse(@response.body) response = JSON.parse(@response.body)
assert_equal expected_links, response['links'] assert_equal expected_links, response['links']
@ -89,8 +89,8 @@ module ActionController
def test_render_only_last_and_next_pagination_links_with_additional_params def test_render_only_last_and_next_pagination_links_with_additional_params
expected_links = { 'self' => "#{WILL_PAGINATE_URI}?page%5Bnumber%5D=1&page%5Bsize%5D=2&teste=additional", expected_links = { 'self' => "#{WILL_PAGINATE_URI}?page%5Bnumber%5D=1&page%5Bsize%5D=2&teste=additional",
'next' => "#{WILL_PAGINATE_URI}?page%5Bnumber%5D=2&page%5Bsize%5D=2&teste=additional", 'next' => "#{WILL_PAGINATE_URI}?page%5Bnumber%5D=2&page%5Bsize%5D=2&teste=additional",
'last' => "#{WILL_PAGINATE_URI}?page%5Bnumber%5D=2&page%5Bsize%5D=2&teste=additional" } 'last' => "#{WILL_PAGINATE_URI}?page%5Bnumber%5D=2&page%5Bsize%5D=2&teste=additional" }
get :render_pagination_using_will_paginate, params: { page: { number: 1, size: 2 }, teste: 'additional' } get :render_pagination_using_will_paginate, params: { page: { number: 1, size: 2 }, teste: 'additional' }
response = JSON.parse(@response.body) response = JSON.parse(@response.body)
assert_equal expected_links, response['links'] assert_equal expected_links, response['links']
@ -98,8 +98,8 @@ module ActionController
def test_render_only_prev_and_first_pagination_links_with_additional_params def test_render_only_prev_and_first_pagination_links_with_additional_params
expected_links = { 'self' => "#{KAMINARI_URI}?page%5Bnumber%5D=3&page%5Bsize%5D=1&teste=additional", expected_links = { 'self' => "#{KAMINARI_URI}?page%5Bnumber%5D=3&page%5Bsize%5D=1&teste=additional",
'first' => "#{KAMINARI_URI}?page%5Bnumber%5D=1&page%5Bsize%5D=1&teste=additional", 'first' => "#{KAMINARI_URI}?page%5Bnumber%5D=1&page%5Bsize%5D=1&teste=additional",
'prev' => "#{KAMINARI_URI}?page%5Bnumber%5D=2&page%5Bsize%5D=1&teste=additional" } 'prev' => "#{KAMINARI_URI}?page%5Bnumber%5D=2&page%5Bsize%5D=1&teste=additional" }
get :render_pagination_using_kaminari, params: { page: { number: 3, size: 1 }, teste: 'additional' } get :render_pagination_using_kaminari, params: { page: { number: 3, size: 1 }, teste: 'additional' }
response = JSON.parse(@response.body) response = JSON.parse(@response.body)
assert_equal expected_links, response['links'] assert_equal expected_links, response['links']

View File

@ -74,7 +74,7 @@ module ActionController
end end
def update_and_render_object_with_cache_enabled def update_and_render_object_with_cache_enabled
@post.updated_at = Time.now @post.updated_at = Time.zone.now
generate_cached_serializer(@post) generate_cached_serializer(@post)
render json: @post render json: @post

View File

@ -1,20 +1,22 @@
require 'test_helper' require 'test_helper'
class ActiveModelSerializers::JsonPointerTest < ActiveSupport::TestCase module ActiveModelSerializers
def test_attribute_pointer class JsonPointerTest < ActiveSupport::TestCase
attribute_name = 'title' def test_attribute_pointer
pointer = ActiveModelSerializers::JsonPointer.new(:attribute, attribute_name) attribute_name = 'title'
assert_equal '/data/attributes/title', pointer pointer = ActiveModelSerializers::JsonPointer.new(:attribute, attribute_name)
end assert_equal '/data/attributes/title', pointer
end
def test_primary_data_pointer def test_primary_data_pointer
pointer = ActiveModelSerializers::JsonPointer.new(:primary_data) pointer = ActiveModelSerializers::JsonPointer.new(:primary_data)
assert_equal '/data', pointer assert_equal '/data', pointer
end end
def test_unkown_data_pointer def test_unkown_data_pointer
assert_raises(TypeError) do assert_raises(TypeError) do
ActiveModelSerializers::JsonPointer.new(:unknown) ActiveModelSerializers::JsonPointer.new(:unknown)
end
end end
end end
end end

View File

@ -1,263 +1,265 @@
require 'test_helper' require 'test_helper'
class ActiveModelSerializers::KeyTransformTest < ActiveSupport::TestCase module ActiveModelSerializers
def test_camel class KeyTransformTest < ActiveSupport::TestCase
obj = Object.new def test_camel
scenarios = [ obj = Object.new
{ scenarios = [
value: { :"some-key" => 'value' }, {
expected: { :SomeKey => 'value' } value: { :"some-key" => 'value' },
}, expected: { SomeKey: 'value' }
{ },
value: { :someKey => 'value' }, {
expected: { :SomeKey => 'value' } value: { someKey: 'value' },
}, expected: { SomeKey: 'value' }
{ },
value: { :some_key => 'value' }, {
expected: { :SomeKey => 'value' } value: { some_key: 'value' },
}, expected: { SomeKey: 'value' }
{ },
value: { 'some-key' => 'value' }, {
expected: { 'SomeKey' => 'value' } value: { 'some-key' => 'value' },
}, expected: { 'SomeKey' => 'value' }
{ },
value: { 'someKey' => 'value' }, {
expected: { 'SomeKey' => 'value' } value: { 'someKey' => 'value' },
}, expected: { 'SomeKey' => 'value' }
{ },
value: { 'some_key' => 'value' }, {
expected: { 'SomeKey' => 'value' } value: { 'some_key' => 'value' },
}, expected: { 'SomeKey' => 'value' }
{ },
value: :"some-value", {
expected: :SomeValue value: :"some-value",
}, expected: :SomeValue
{ },
value: :some_value, {
expected: :SomeValue value: :some_value,
}, expected: :SomeValue
{ },
value: :someValue, {
expected: :SomeValue value: :someValue,
}, expected: :SomeValue
{ },
value: 'some-value', {
expected: 'SomeValue' value: 'some-value',
}, expected: 'SomeValue'
{ },
value: 'someValue', {
expected: 'SomeValue' value: 'someValue',
}, expected: 'SomeValue'
{ },
value: 'some_value', {
expected: 'SomeValue' value: 'some_value',
}, expected: 'SomeValue'
{ },
value: obj, {
expected: obj value: obj,
}, expected: obj
{ },
value: nil, {
expected: nil value: nil,
} expected: nil
] }
scenarios.each do |s| ]
result = ActiveModelSerializers::KeyTransform.camel(s[:value]) scenarios.each do |s|
assert_equal s[:expected], result result = ActiveModelSerializers::KeyTransform.camel(s[:value])
assert_equal s[:expected], result
end
end end
end
def test_camel_lower def test_camel_lower
obj = Object.new obj = Object.new
scenarios = [ scenarios = [
{ {
value: { :"some-key" => 'value' }, value: { :"some-key" => 'value' },
expected: { :someKey => 'value' } expected: { someKey: 'value' }
}, },
{ {
value: { :SomeKey => 'value' }, value: { SomeKey: 'value' },
expected: { :someKey => 'value' } expected: { someKey: 'value' }
}, },
{ {
value: { :some_key => 'value' }, value: { some_key: 'value' },
expected: { :someKey => 'value' } expected: { someKey: 'value' }
}, },
{ {
value: { 'some-key' => 'value' }, value: { 'some-key' => 'value' },
expected: { 'someKey' => 'value' } expected: { 'someKey' => 'value' }
}, },
{ {
value: { 'SomeKey' => 'value' }, value: { 'SomeKey' => 'value' },
expected: { 'someKey' => 'value' } expected: { 'someKey' => 'value' }
}, },
{ {
value: { 'some_key' => 'value' }, value: { 'some_key' => 'value' },
expected: { 'someKey' => 'value' } expected: { 'someKey' => 'value' }
}, },
{ {
value: :"some-value", value: :"some-value",
expected: :someValue expected: :someValue
}, },
{ {
value: :SomeValue, value: :SomeValue,
expected: :someValue expected: :someValue
}, },
{ {
value: :some_value, value: :some_value,
expected: :someValue expected: :someValue
}, },
{ {
value: 'some-value', value: 'some-value',
expected: 'someValue' expected: 'someValue'
}, },
{ {
value: 'SomeValue', value: 'SomeValue',
expected: 'someValue' expected: 'someValue'
}, },
{ {
value: 'some_value', value: 'some_value',
expected: 'someValue' expected: 'someValue'
}, },
{ {
value: obj, value: obj,
expected: obj expected: obj
}, },
{ {
value: nil, value: nil,
expected: nil expected: nil
} }
] ]
scenarios.each do |s| scenarios.each do |s|
result = ActiveModelSerializers::KeyTransform.camel_lower(s[:value]) result = ActiveModelSerializers::KeyTransform.camel_lower(s[:value])
assert_equal s[:expected], result assert_equal s[:expected], result
end
end end
end
def test_dash def test_dash
obj = Object.new obj = Object.new
scenarios = [ scenarios = [
{ {
value: { :some_key => 'value' }, value: { some_key: 'value' },
expected: { :"some-key" => 'value' } expected: { :"some-key" => 'value' }
}, },
{ {
value: { 'some_key' => 'value' }, value: { 'some_key' => 'value' },
expected: { 'some-key' => 'value' } expected: { 'some-key' => 'value' }
}, },
{ {
value: { :SomeKey => 'value' }, value: { SomeKey: 'value' },
expected: { :"some-key" => 'value' } expected: { :"some-key" => 'value' }
}, },
{ {
value: { 'SomeKey' => 'value' }, value: { 'SomeKey' => 'value' },
expected: { 'some-key' => 'value' } expected: { 'some-key' => 'value' }
}, },
{ {
value: { :someKey => 'value' }, value: { someKey: 'value' },
expected: { :"some-key" => 'value' } expected: { :"some-key" => 'value' }
}, },
{ {
value: { 'someKey' => 'value' }, value: { 'someKey' => 'value' },
expected: { 'some-key' => 'value' } expected: { 'some-key' => 'value' }
}, },
{ {
value: :some_value, value: :some_value,
expected: :"some-value" expected: :"some-value"
}, },
{ {
value: :SomeValue, value: :SomeValue,
expected: :"some-value" expected: :"some-value"
}, },
{ {
value: 'SomeValue', value: 'SomeValue',
expected: 'some-value' expected: 'some-value'
}, },
{ {
value: :someValue, value: :someValue,
expected: :"some-value" expected: :"some-value"
}, },
{ {
value: 'someValue', value: 'someValue',
expected: 'some-value' expected: 'some-value'
}, },
{ {
value: obj, value: obj,
expected: obj expected: obj
}, },
{ {
value: nil, value: nil,
expected: nil expected: nil
} }
] ]
scenarios.each do |s| scenarios.each do |s|
result = ActiveModelSerializers::KeyTransform.dash(s[:value]) result = ActiveModelSerializers::KeyTransform.dash(s[:value])
assert_equal s[:expected], result assert_equal s[:expected], result
end
end end
end
def test_underscore def test_underscore
obj = Object.new obj = Object.new
scenarios = [ scenarios = [
{ {
value: { :"some-key" => 'value' }, value: { :"some-key" => 'value' },
expected: { :some_key => 'value' } expected: { some_key: 'value' }
}, },
{ {
value: { 'some-key' => 'value' }, value: { 'some-key' => 'value' },
expected: { 'some_key' => 'value' } expected: { 'some_key' => 'value' }
}, },
{ {
value: { :SomeKey => 'value' }, value: { SomeKey: 'value' },
expected: { :some_key => 'value' } expected: { some_key: 'value' }
}, },
{ {
value: { 'SomeKey' => 'value' }, value: { 'SomeKey' => 'value' },
expected: { 'some_key' => 'value' } expected: { 'some_key' => 'value' }
}, },
{ {
value: { :someKey => 'value' }, value: { someKey: 'value' },
expected: { :some_key => 'value' } expected: { some_key: 'value' }
}, },
{ {
value: { 'someKey' => 'value' }, value: { 'someKey' => 'value' },
expected: { 'some_key' => 'value' } expected: { 'some_key' => 'value' }
}, },
{ {
value: :"some-value", value: :"some-value",
expected: :some_value expected: :some_value
}, },
{ {
value: :SomeValue, value: :SomeValue,
expected: :some_value expected: :some_value
}, },
{ {
value: :someValue, value: :someValue,
expected: :some_value expected: :some_value
}, },
{ {
value: 'some-value', value: 'some-value',
expected: 'some_value' expected: 'some_value'
}, },
{ {
value: 'SomeValue', value: 'SomeValue',
expected: 'some_value' expected: 'some_value'
}, },
{ {
value: 'someValue', value: 'someValue',
expected: 'some_value' expected: 'some_value'
}, },
{ {
value: obj, value: obj,
expected: obj expected: obj
}, },
{ {
value: nil, value: nil,
expected: nil expected: nil
} }
] ]
scenarios.each do |s| scenarios.each do |s|
result = ActiveModelSerializers::KeyTransform.underscore(s[:value]) result = ActiveModelSerializers::KeyTransform.underscore(s[:value])
assert_equal s[:expected], result assert_equal s[:expected], result
end
end end
end end
end end

View File

@ -1,9 +1,11 @@
require 'test_helper' require 'test_helper'
class ActiveModelSerializers::ModelTest < ActiveSupport::TestCase module ActiveModelSerializers
include ActiveModel::Serializer::Lint::Tests class ModelTest < ActiveSupport::TestCase
include ActiveModel::Serializer::Lint::Tests
def setup def setup
@resource = ActiveModelSerializers::Model.new @resource = ActiveModelSerializers::Model.new
end
end end
end end

View File

@ -44,7 +44,7 @@ class JsonApiRendererTest < ActionDispatch::IntegrationTest
Rails.application.routes.draw do Rails.application.routes.draw do
ActiveSupport::Deprecation.silence do ActiveSupport::Deprecation.silence do
match ':action', :to => TestController, via: [:get, :post] match ':action', to: TestController, via: [:get, :post]
end end
end end
end end
@ -95,7 +95,7 @@ class JsonApiRendererTest < ActionDispatch::IntegrationTest
Rails.application.routes.draw do Rails.application.routes.draw do
ActiveSupport::Deprecation.silence do ActiveSupport::Deprecation.silence do
match ':action', :to => TestController, via: [:get, :post] match ':action', to: TestController, via: [:get, :post]
end end
end end
end end

View File

@ -28,8 +28,8 @@ module ActiveModelSerializers
def test_transform_default def test_transform_default
mock_request mock_request
assert_equal({ assert_equal({
blog: { id: 1, special_attribute: 'neat', articles: nil } blog: { id: 1, special_attribute: 'neat', articles: nil }
}, @adapter.serializable_hash) }, @adapter.serializable_hash)
end end
def test_transform_global_config def test_transform_global_config
@ -38,8 +38,8 @@ module ActiveModelSerializers
@adapter.serializable_hash @adapter.serializable_hash
end end
assert_equal({ assert_equal({
blog: { id: 1, specialAttribute: 'neat', articles: nil } blog: { id: 1, specialAttribute: 'neat', articles: nil }
}, result) }, result)
end end
def test_transform_serialization_ctx_overrides_global_config def test_transform_serialization_ctx_overrides_global_config
@ -48,8 +48,8 @@ module ActiveModelSerializers
@adapter.serializable_hash @adapter.serializable_hash
end end
assert_equal({ assert_equal({
Blog: { Id: 1, SpecialAttribute: 'neat', Articles: nil } Blog: { Id: 1, SpecialAttribute: 'neat', Articles: nil }
}, result) }, result)
end end
def test_transform_undefined def test_transform_undefined
@ -63,29 +63,29 @@ module ActiveModelSerializers
def test_transform_dash def test_transform_dash
mock_request(:dash) mock_request(:dash)
assert_equal({ assert_equal({
blog: { id: 1, :"special-attribute" => 'neat', articles: nil } blog: { id: 1, :"special-attribute" => 'neat', articles: nil }
}, @adapter.serializable_hash) }, @adapter.serializable_hash)
end end
def test_transform_unaltered def test_transform_unaltered
mock_request(:unaltered) mock_request(:unaltered)
assert_equal({ assert_equal({
blog: { id: 1, special_attribute: 'neat', articles: nil } blog: { id: 1, special_attribute: 'neat', articles: nil }
}, @adapter.serializable_hash) }, @adapter.serializable_hash)
end end
def test_transform_camel def test_transform_camel
mock_request(:camel) mock_request(:camel)
assert_equal({ assert_equal({
Blog: { Id: 1, SpecialAttribute: 'neat', Articles: nil } Blog: { Id: 1, SpecialAttribute: 'neat', Articles: nil }
}, @adapter.serializable_hash) }, @adapter.serializable_hash)
end end
def test_transform_camel_lower def test_transform_camel_lower
mock_request(:camel_lower) mock_request(:camel_lower)
assert_equal({ assert_equal({
blog: { id: 1, specialAttribute: 'neat', articles: nil } blog: { id: 1, specialAttribute: 'neat', articles: nil }
}, @adapter.serializable_hash) }, @adapter.serializable_hash)
end end
end end
end end

View File

@ -12,8 +12,8 @@ module ActiveModelSerializers
def test_active_model_with_error def test_active_model_with_error
options = { options = {
serializer: ActiveModel::Serializer::ErrorSerializer, serializer: ActiveModel::Serializer::ErrorSerializer,
adapter: :json_api adapter: :json_api
} }
@resource.errors.add(:name, 'cannot be nil') @resource.errors.add(:name, 'cannot be nil')
@ -23,7 +23,7 @@ module ActiveModelSerializers
assert_equal serializable_resource.serializer_instance.object, @resource assert_equal serializable_resource.serializer_instance.object, @resource
expected_errors_object = { expected_errors_object = {
:errors => [ errors: [
{ {
source: { pointer: '/data/attributes/name' }, source: { pointer: '/data/attributes/name' },
detail: 'cannot be nil' detail: 'cannot be nil'
@ -35,8 +35,8 @@ module ActiveModelSerializers
def test_active_model_with_multiple_errors def test_active_model_with_multiple_errors
options = { options = {
serializer: ActiveModel::Serializer::ErrorSerializer, serializer: ActiveModel::Serializer::ErrorSerializer,
adapter: :json_api adapter: :json_api
} }
@resource.errors.add(:name, 'cannot be nil') @resource.errors.add(:name, 'cannot be nil')
@ -48,10 +48,10 @@ module ActiveModelSerializers
assert_equal serializable_resource.serializer_instance.object, @resource assert_equal serializable_resource.serializer_instance.object, @resource
expected_errors_object = { expected_errors_object = {
:errors => [ errors: [
{ :source => { :pointer => '/data/attributes/name' }, :detail => 'cannot be nil' }, { source: { pointer: '/data/attributes/name' }, detail: 'cannot be nil' },
{ :source => { :pointer => '/data/attributes/name' }, :detail => 'must be longer' }, { source: { pointer: '/data/attributes/name' }, detail: 'must be longer' },
{ :source => { :pointer => '/data/attributes/id' }, :detail => 'must be a uuid' } { source: { pointer: '/data/attributes/id' }, detail: 'must be a uuid' }
] ]
} }
assert_equal serializable_resource.as_json, expected_errors_object assert_equal serializable_resource.as_json, expected_errors_object

View File

@ -112,14 +112,14 @@ module ActiveModelSerializers
adapter = ActiveModelSerializers::Adapter::JsonApi.new(serializer) adapter = ActiveModelSerializers::Adapter::JsonApi.new(serializer)
assert_equal({ assert_equal({
data: { data: {
id: '1', id: '1',
type: 'posts', type: 'posts',
relationships: { relationships: {
tags: { data: [@tag.as_json] } tags: { data: [@tag.as_json] }
} }
} }
}, adapter.serializable_hash) }, adapter.serializable_hash)
end end
def test_has_many_with_virtual_value def test_has_many_with_virtual_value
@ -127,16 +127,16 @@ module ActiveModelSerializers
adapter = ActiveModelSerializers::Adapter::JsonApi.new(serializer) adapter = ActiveModelSerializers::Adapter::JsonApi.new(serializer)
assert_equal({ assert_equal({
data: { data: {
id: '1', id: '1',
type: 'virtual-values', type: 'virtual-values',
relationships: { relationships: {
maker: { data: { type: 'makers', id: '1' } }, maker: { data: { type: 'makers', id: '1' } },
reviews: { data: [{ type: 'reviews', id: '1' }, reviews: { data: [{ type: 'reviews', id: '1' },
{ type: 'reviews', id: '2' }] } { type: 'reviews', id: '2' }] }
} }
} }
}, adapter.serializable_hash) }, adapter.serializable_hash)
end end
end end
end end

View File

@ -22,13 +22,11 @@ module ActiveModelSerializers
adapter = ActiveModelSerializers::Adapter::JsonApi.new(serializer) adapter = ActiveModelSerializers::Adapter::JsonApi.new(serializer)
assert_equal({ assert_equal({
reviews: { data: [ reviews: { data: [{ type: 'comments', id: '1' },
{ type: 'comments', id: '1' }, { type: 'comments', id: '2' }] },
{ type: 'comments', id: '2' } writer: { data: { type: 'authors', id: '1' } },
] }, site: { data: { type: 'blogs', id: '1' } }
writer: { data: { type: 'authors', id: '1' } }, }, adapter.serializable_hash[:data][:relationships])
site: { data: { type: 'blogs', id: '1' } }
}, adapter.serializable_hash[:data][:relationships])
end end
end end
end end

View File

@ -17,7 +17,7 @@ module ActiveModelSerializers
@first_post = Post.new(id: 10, title: 'Hello!!', body: 'Hello, world!!') @first_post = Post.new(id: 10, title: 'Hello!!', body: 'Hello, world!!')
@second_post = Post.new(id: 20, title: 'New Post', body: 'Body') @second_post = Post.new(id: 20, title: 'New Post', body: 'Body')
@third_post = Post.new(id: 30, title: 'Yet Another Post', body: 'Body') @third_post = Post.new(id: 30, title: 'Yet Another Post', body: 'Body')
@blog = Blog.new({ name: 'AMS Blog' }) @blog = Blog.new(name: 'AMS Blog')
@first_comment = Comment.new(id: 1, body: 'ZOMG A COMMENT') @first_comment = Comment.new(id: 1, body: 'ZOMG A COMMENT')
@second_comment = Comment.new(id: 2, body: 'ZOMG ANOTHER COMMENT') @second_comment = Comment.new(id: 2, body: 'ZOMG ANOTHER COMMENT')
@first_post.blog = @blog @first_post.blog = @blog

View File

@ -13,11 +13,11 @@ module ActiveModelSerializers
def setup def setup
ActionController::Base.cache_store.clear ActionController::Base.cache_store.clear
@array = [ @array = [
Profile.new({ id: 1, name: 'Name 1', description: 'Description 1', comments: 'Comments 1' }), Profile.new(id: 1, name: 'Name 1', description: 'Description 1', comments: 'Comments 1'),
Profile.new({ id: 2, name: 'Name 2', description: 'Description 2', comments: 'Comments 2' }), Profile.new(id: 2, name: 'Name 2', description: 'Description 2', comments: 'Comments 2'),
Profile.new({ id: 3, name: 'Name 3', description: 'Description 3', comments: 'Comments 3' }), Profile.new(id: 3, name: 'Name 3', description: 'Description 3', comments: 'Comments 3'),
Profile.new({ id: 4, name: 'Name 4', description: 'Description 4', comments: 'Comments 4' }), Profile.new(id: 4, name: 'Name 4', description: 'Description 4', comments: 'Comments 4'),
Profile.new({ id: 5, name: 'Name 5', description: 'Description 5', comments: 'Comments 5' }) Profile.new(id: 5, name: 'Name 5', description: 'Description 5', comments: 'Comments 5')
] ]
end end
@ -122,7 +122,7 @@ module ActiveModelSerializers
end end
def test_pagination_links_with_additional_params def test_pagination_links_with_additional_params
adapter = load_adapter(using_will_paginate, mock_request({ test: 'test' })) adapter = load_adapter(using_will_paginate, mock_request(test: 'test'))
assert_equal expected_response_with_pagination_links_and_additional_params, assert_equal expected_response_with_pagination_links_and_additional_params,
adapter.serializable_hash adapter.serializable_hash

View File

@ -68,9 +68,9 @@ module ActiveModel
adapter: :json_api adapter: :json_api
).serializable_hash ).serializable_hash
expected = { expected = {
:data => [ data: [
{ :id => '1337', :type => 'posts', :meta => { :"comments-count" => 0 } }, { id: '1337', type: 'posts', meta: { :"comments-count" => 0 } },
{ :id => '1339', :type => 'posts', :meta => { :"comments-count" => 1 } } { id: '1339', type: 'posts', meta: { :"comments-count" => 1 } }
] ]
} }
assert_equal(expected, hash) assert_equal(expected, hash)

View File

@ -70,33 +70,33 @@ module ActiveModelSerializers
adapter = ActiveModelSerializers::Adapter::JsonApi.new(serializer, @options) adapter = ActiveModelSerializers::Adapter::JsonApi.new(serializer, @options)
result = adapter.serializable_hash result = adapter.serializable_hash
assert_equal({ assert_equal({
data: { data: {
id: '1337', id: '1337',
type: 'posts', type: 'posts',
attributes: { attributes: {
title: 'Title 1', title: 'Title 1',
body: 'Body 1', body: 'Body 1',
:"publish-at" => @publish_at :"publish-at" => @publish_at
}, },
relationships: { relationships: {
author: { author: {
data: { id: '1', type: 'authors' } data: { id: '1', type: 'authors' }
}, },
comments: { comments: {
data: [ data: [
{ id: '7', type: 'comments' }, { id: '7', type: 'comments' },
{ id: '12', type: 'comments' } { id: '12', type: 'comments' }
] ]
} }
}, },
links: { links: {
self: 'http://example.com/posts/1337', self: 'http://example.com/posts/1337',
:"post-authors" => 'http://example.com/posts/1337/authors', :"post-authors" => 'http://example.com/posts/1337/authors',
:"subscriber-comments" => 'http://example.com/posts/1337/comments' :"subscriber-comments" => 'http://example.com/posts/1337/comments'
}, },
meta: { rating: 5, :"favorite-count" => 10 } meta: { rating: 5, :"favorite-count" => 10 }
} }
}, result) }, result)
end end
def test_success_document_transform_global_config def test_success_document_transform_global_config
@ -107,33 +107,33 @@ module ActiveModelSerializers
adapter.serializable_hash adapter.serializable_hash
end end
assert_equal({ assert_equal({
data: { data: {
id: '1337', id: '1337',
type: 'posts', type: 'posts',
attributes: { attributes: {
title: 'Title 1', title: 'Title 1',
body: 'Body 1', body: 'Body 1',
publishAt: @publish_at publishAt: @publish_at
}, },
relationships: { relationships: {
author: { author: {
data: { id: '1', type: 'authors' } data: { id: '1', type: 'authors' }
}, },
comments: { comments: {
data: [ data: [
{ id: '7', type: 'comments' }, { id: '7', type: 'comments' },
{ id: '12', type: 'comments' } { id: '12', type: 'comments' }
] ]
} }
}, },
links: { links: {
self: 'http://example.com/posts/1337', self: 'http://example.com/posts/1337',
postAuthors: 'http://example.com/posts/1337/authors', postAuthors: 'http://example.com/posts/1337/authors',
subscriberComments: 'http://example.com/posts/1337/comments' subscriberComments: 'http://example.com/posts/1337/comments'
}, },
meta: { rating: 5, favoriteCount: 10 } meta: { rating: 5, favoriteCount: 10 }
} }
}, result) }, result)
end end
def test_success_doc_transform_serialization_ctx_overrides_global def test_success_doc_transform_serialization_ctx_overrides_global
@ -144,33 +144,33 @@ module ActiveModelSerializers
adapter.serializable_hash adapter.serializable_hash
end end
assert_equal({ assert_equal({
Data: { Data: {
Id: '1337', Id: '1337',
Type: 'Posts', Type: 'Posts',
Attributes: { Attributes: {
Title: 'Title 1', Title: 'Title 1',
Body: 'Body 1', Body: 'Body 1',
PublishAt: @publish_at PublishAt: @publish_at
}, },
Relationships: { Relationships: {
Author: { Author: {
Data: { Id: '1', Type: 'Authors' } Data: { Id: '1', Type: 'Authors' }
}, },
Comments: { Comments: {
Data: [ Data: [
{ Id: '7', Type: 'Comments' }, { Id: '7', Type: 'Comments' },
{ Id: '12', Type: 'Comments' } { Id: '12', Type: 'Comments' }
] ]
} }
}, },
Links: { Links: {
Self: 'http://example.com/posts/1337', Self: 'http://example.com/posts/1337',
PostAuthors: 'http://example.com/posts/1337/authors', PostAuthors: 'http://example.com/posts/1337/authors',
SubscriberComments: 'http://example.com/posts/1337/comments' SubscriberComments: 'http://example.com/posts/1337/comments'
}, },
Meta: { Rating: 5, FavoriteCount: 10 } Meta: { Rating: 5, FavoriteCount: 10 }
} }
}, result) }, result)
end end
def test_success_document_transform_dash def test_success_document_transform_dash
@ -179,33 +179,33 @@ module ActiveModelSerializers
adapter = ActiveModelSerializers::Adapter::JsonApi.new(serializer, @options) adapter = ActiveModelSerializers::Adapter::JsonApi.new(serializer, @options)
result = adapter.serializable_hash result = adapter.serializable_hash
assert_equal({ assert_equal({
data: { data: {
id: '1337', id: '1337',
type: 'posts', type: 'posts',
attributes: { attributes: {
title: 'Title 1', title: 'Title 1',
body: 'Body 1', body: 'Body 1',
:"publish-at" => @publish_at :"publish-at" => @publish_at
}, },
relationships: { relationships: {
author: { author: {
data: { id: '1', type: 'authors' } data: { id: '1', type: 'authors' }
}, },
comments: { comments: {
data: [ data: [
{ id: '7', type: 'comments' }, { id: '7', type: 'comments' },
{ id: '12', type: 'comments' } { id: '12', type: 'comments' }
] ]
} }
}, },
links: { links: {
self: 'http://example.com/posts/1337', self: 'http://example.com/posts/1337',
:"post-authors" => 'http://example.com/posts/1337/authors', :"post-authors" => 'http://example.com/posts/1337/authors',
:"subscriber-comments" => 'http://example.com/posts/1337/comments' :"subscriber-comments" => 'http://example.com/posts/1337/comments'
}, },
meta: { rating: 5, :"favorite-count" => 10 } meta: { rating: 5, :"favorite-count" => 10 }
} }
}, result) }, result)
end end
def test_success_document_transform_unaltered def test_success_document_transform_unaltered
@ -214,33 +214,33 @@ module ActiveModelSerializers
adapter = ActiveModelSerializers::Adapter::JsonApi.new(serializer, @options) adapter = ActiveModelSerializers::Adapter::JsonApi.new(serializer, @options)
result = adapter.serializable_hash result = adapter.serializable_hash
assert_equal({ assert_equal({
data: { data: {
id: '1337', id: '1337',
type: 'posts', type: 'posts',
attributes: { attributes: {
title: 'Title 1', title: 'Title 1',
body: 'Body 1', body: 'Body 1',
publish_at: @publish_at publish_at: @publish_at
}, },
relationships: { relationships: {
author: { author: {
data: { id: '1', type: 'authors' } data: { id: '1', type: 'authors' }
}, },
comments: { comments: {
data: [ data: [
{ id: '7', type: 'comments' }, { id: '7', type: 'comments' },
{ id: '12', type: 'comments' } { id: '12', type: 'comments' }
] ]
} }
}, },
links: { links: {
self: 'http://example.com/posts/1337', self: 'http://example.com/posts/1337',
post_authors: 'http://example.com/posts/1337/authors', post_authors: 'http://example.com/posts/1337/authors',
subscriber_comments: 'http://example.com/posts/1337/comments' subscriber_comments: 'http://example.com/posts/1337/comments'
}, },
meta: { rating: 5, favorite_count: 10 } meta: { rating: 5, favorite_count: 10 }
} }
}, result) }, result)
end end
def test_success_document_transform_undefined def test_success_document_transform_undefined
@ -259,33 +259,33 @@ module ActiveModelSerializers
adapter = ActiveModelSerializers::Adapter::JsonApi.new(serializer, @options) adapter = ActiveModelSerializers::Adapter::JsonApi.new(serializer, @options)
result = adapter.serializable_hash result = adapter.serializable_hash
assert_equal({ assert_equal({
Data: { Data: {
Id: '1337', Id: '1337',
Type: 'Posts', Type: 'Posts',
Attributes: { Attributes: {
Title: 'Title 1', Title: 'Title 1',
Body: 'Body 1', Body: 'Body 1',
PublishAt: @publish_at PublishAt: @publish_at
}, },
Relationships: { Relationships: {
Author: { Author: {
Data: { Id: '1', Type: 'Authors' } Data: { Id: '1', Type: 'Authors' }
}, },
Comments: { Comments: {
Data: [ Data: [
{ Id: '7', Type: 'Comments' }, { Id: '7', Type: 'Comments' },
{ Id: '12', Type: 'Comments' } { Id: '12', Type: 'Comments' }
] ]
} }
}, },
Links: { Links: {
Self: 'http://example.com/posts/1337', Self: 'http://example.com/posts/1337',
PostAuthors: 'http://example.com/posts/1337/authors', PostAuthors: 'http://example.com/posts/1337/authors',
SubscriberComments: 'http://example.com/posts/1337/comments' SubscriberComments: 'http://example.com/posts/1337/comments'
}, },
Meta: { Rating: 5, FavoriteCount: 10 } Meta: { Rating: 5, FavoriteCount: 10 }
} }
}, result) }, result)
end end
def test_success_document_transform_camel_lower def test_success_document_transform_camel_lower
@ -294,33 +294,33 @@ module ActiveModelSerializers
adapter = ActiveModelSerializers::Adapter::JsonApi.new(serializer, @options) adapter = ActiveModelSerializers::Adapter::JsonApi.new(serializer, @options)
result = adapter.serializable_hash result = adapter.serializable_hash
assert_equal({ assert_equal({
data: { data: {
id: '1337', id: '1337',
type: 'posts', type: 'posts',
attributes: { attributes: {
title: 'Title 1', title: 'Title 1',
body: 'Body 1', body: 'Body 1',
publishAt: @publish_at publishAt: @publish_at
}, },
relationships: { relationships: {
author: { author: {
data: { id: '1', type: 'authors' } data: { id: '1', type: 'authors' }
}, },
comments: { comments: {
data: [ data: [
{ id: '7', type: 'comments' }, { id: '7', type: 'comments' },
{ id: '12', type: 'comments' } { id: '12', type: 'comments' }
] ]
} }
}, },
links: { links: {
self: 'http://example.com/posts/1337', self: 'http://example.com/posts/1337',
postAuthors: 'http://example.com/posts/1337/authors', postAuthors: 'http://example.com/posts/1337/authors',
subscriberComments: 'http://example.com/posts/1337/comments' subscriberComments: 'http://example.com/posts/1337/comments'
}, },
meta: { rating: 5, favoriteCount: 10 } meta: { rating: 5, favoriteCount: 10 }
} }
}, result) }, result)
end end
def test_error_document_transform_default def test_error_document_transform_default
@ -332,14 +332,14 @@ module ActiveModelSerializers
adapter = ActiveModelSerializers::Adapter::JsonApi.new(serializer, @options) adapter = ActiveModelSerializers::Adapter::JsonApi.new(serializer, @options)
result = adapter.serializable_hash result = adapter.serializable_hash
expected_errors_object = { expected_errors_object = {
:errors => [ errors: [
{ {
:source => { :pointer => '/data/attributes/published-at' }, source: { pointer: '/data/attributes/published-at' },
:detail => 'must be in the future' detail: 'must be in the future'
}, },
{ {
:source => { :pointer => '/data/attributes/title' }, source: { pointer: '/data/attributes/title' },
:detail => 'must be longer' detail: 'must be longer'
} }
] ]
} }
@ -357,14 +357,14 @@ module ActiveModelSerializers
adapter.serializable_hash adapter.serializable_hash
end end
expected_errors_object = { expected_errors_object = {
:Errors => [ Errors: [
{ {
:Source => { :Pointer => '/data/attributes/PublishedAt' }, Source: { Pointer: '/data/attributes/PublishedAt' },
:Detail => 'must be in the future' Detail: 'must be in the future'
}, },
{ {
:Source => { :Pointer => '/data/attributes/Title' }, Source: { Pointer: '/data/attributes/Title' },
:Detail => 'must be longer' Detail: 'must be longer'
} }
] ]
} }
@ -382,14 +382,14 @@ module ActiveModelSerializers
adapter.serializable_hash adapter.serializable_hash
end end
expected_errors_object = { expected_errors_object = {
:Errors => [ Errors: [
{ {
:Source => { :Pointer => '/data/attributes/PublishedAt' }, Source: { Pointer: '/data/attributes/PublishedAt' },
:Detail => 'must be in the future' Detail: 'must be in the future'
}, },
{ {
:Source => { :Pointer => '/data/attributes/Title' }, Source: { Pointer: '/data/attributes/Title' },
:Detail => 'must be longer' Detail: 'must be longer'
} }
] ]
} }
@ -408,14 +408,14 @@ module ActiveModelSerializers
result = adapter.serializable_hash result = adapter.serializable_hash
expected_errors_object = { expected_errors_object = {
:errors => [ errors: [
{ {
:source => { :pointer => '/data/attributes/published-at' }, source: { pointer: '/data/attributes/published-at' },
:detail => 'must be in the future' detail: 'must be in the future'
}, },
{ {
:source => { :pointer => '/data/attributes/title' }, source: { pointer: '/data/attributes/title' },
:detail => 'must be longer' detail: 'must be longer'
} }
] ]
} }
@ -434,9 +434,9 @@ module ActiveModelSerializers
result = adapter.serializable_hash result = adapter.serializable_hash
expected_errors_object = { expected_errors_object = {
:errors => [ errors: [
{ :source => { :pointer => '/data/attributes/published_at' }, :detail => 'must be in the future' }, { source: { pointer: '/data/attributes/published_at' }, detail: 'must be in the future' },
{ :source => { :pointer => '/data/attributes/title' }, :detail => 'must be longer' } { source: { pointer: '/data/attributes/title' }, detail: 'must be longer' }
] ]
} }
assert_equal expected_errors_object, result assert_equal expected_errors_object, result
@ -470,9 +470,9 @@ module ActiveModelSerializers
result = adapter.serializable_hash result = adapter.serializable_hash
expected_errors_object = { expected_errors_object = {
:Errors => [ Errors: [
{ :Source => { :Pointer => '/data/attributes/PublishedAt' }, :Detail => 'must be in the future' }, { Source: { Pointer: '/data/attributes/PublishedAt' }, Detail: 'must be in the future' },
{ :Source => { :Pointer => '/data/attributes/Title' }, :Detail => 'must be longer' } { Source: { Pointer: '/data/attributes/Title' }, Detail: 'must be longer' }
] ]
} }
assert_equal expected_errors_object, result assert_equal expected_errors_object, result
@ -490,9 +490,9 @@ module ActiveModelSerializers
result = adapter.serializable_hash result = adapter.serializable_hash
expected_errors_object = { expected_errors_object = {
:errors => [ errors: [
{ :source => { :pointer => '/data/attributes/publishedAt' }, :detail => 'must be in the future' }, { source: { pointer: '/data/attributes/publishedAt' }, detail: 'must be in the future' },
{ :source => { :pointer => '/data/attributes/title' }, :detail => 'must be longer' } { source: { pointer: '/data/attributes/title' }, detail: 'must be longer' }
] ]
} }
assert_equal expected_errors_object, result assert_equal expected_errors_object, result

View File

@ -47,7 +47,7 @@ module ActiveModel
assert_equal(expected_type, hash.fetch(:data).fetch(:type)) assert_equal(expected_type, hash.fetch(:data).fetch(:type))
end end
def with_jsonapi_resource_type inflection def with_jsonapi_resource_type(inflection)
old_inflection = ActiveModelSerializers.config.jsonapi_resource_type old_inflection = ActiveModelSerializers.config.jsonapi_resource_type
ActiveModelSerializers.config.jsonapi_resource_type = inflection ActiveModelSerializers.config.jsonapi_resource_type = inflection
yield yield

View File

@ -32,14 +32,14 @@ module ActiveModelSerializers
adapter = ActiveModelSerializers::Adapter::Json.new(serializer) adapter = ActiveModelSerializers::Adapter::Json.new(serializer)
assert_equal({ assert_equal({
id: 1, id: 1,
reviews: [ reviews: [
{ id: 1, body: 'ZOMG A COMMENT' }, { id: 1, body: 'ZOMG A COMMENT' },
{ id: 2, body: 'ZOMG ANOTHER COMMENT' } { id: 2, body: 'ZOMG ANOTHER COMMENT' }
], ],
writer: { id: 1, name: 'Steve K.' }, writer: { id: 1, name: 'Steve K.' },
site: { id: 1, name: 'My Blog!!' } site: { id: 1, name: 'My Blog!!' }
}, adapter.serializable_hash[:post]) }, adapter.serializable_hash[:post])
end end
end end
end end

View File

@ -4,7 +4,7 @@ module ActiveModelSerializers
module Adapter module Adapter
class NullTest < ActiveSupport::TestCase class NullTest < ActiveSupport::TestCase
def setup def setup
profile = Profile.new({ name: 'Name 1', description: 'Description 1', comments: 'Comments 1' }) profile = Profile.new(name: 'Name 1', description: 'Description 1', comments: 'Comments 1')
serializer = ProfileSerializer.new(profile) serializer = ProfileSerializer.new(profile)
@adapter = Null.new(serializer) @adapter = Null.new(serializer)
@ -20,4 +20,3 @@ module ActiveModelSerializers
end end
end end
end end

View File

@ -27,11 +27,11 @@ module ActiveModel
id: 1, id: 1,
title: 'headshot-1.jpg', title: 'headshot-1.jpg',
imageable: { imageable: {
type: 'employee', type: 'employee',
employee: { employee: {
id: 42, id: 42,
name: 'Zoop Zoopler' name: 'Zoop Zoopler'
} }
} }
} }

View File

@ -51,7 +51,7 @@ module ActiveModelSerializers
end end
def test_create_adapter_with_override def test_create_adapter_with_override
adapter = ActiveModelSerializers::Adapter.create(@serializer, { adapter: :json_api }) adapter = ActiveModelSerializers::Adapter.create(@serializer, adapter: :json_api)
assert_equal ActiveModelSerializers::Adapter::JsonApi, adapter.class assert_equal ActiveModelSerializers::Adapter::JsonApi, adapter.class
end end

View File

@ -86,7 +86,7 @@ class ApiAssertion
} }
] ]
} }
} }
end end
def assert_equal(expected, actual, message) def assert_equal(expected, actual, message)

View File

@ -101,7 +101,7 @@ module ActiveModelSerializers
uncached_author_serializer = AuthorSerializer.new(uncached_author) uncached_author_serializer = AuthorSerializer.new(uncached_author)
render_object_with_cache(uncached_author) render_object_with_cache(uncached_author)
key = "#{uncached_author_serializer.class._cache_key}/#{uncached_author_serializer.object.id}-#{uncached_author_serializer.object.updated_at.strftime("%Y%m%d%H%M%S%9N")}" key = "#{uncached_author_serializer.class._cache_key}/#{uncached_author_serializer.object.id}-#{uncached_author_serializer.object.updated_at.strftime('%Y%m%d%H%M%S%9N')}"
key = "#{key}/#{adapter.cache_key}" key = "#{key}/#{adapter.cache_key}"
assert_equal(uncached_author_serializer.attributes.to_json, cache_store.fetch(key).to_json) assert_equal(uncached_author_serializer.attributes.to_json, cache_store.fetch(key).to_json)
end end

View File

@ -11,7 +11,7 @@ module ActiveModel
@comment = Comment.new @comment = Comment.new
@post = Post.new @post = Post.new
@resource = build_named_collection @comment, @post @resource = build_named_collection @comment, @post
@serializer = collection_serializer.new(@resource, { some: :options }) @serializer = collection_serializer.new(@resource, some: :options)
end end
def collection_serializer def collection_serializer
@ -44,7 +44,7 @@ module ActiveModel
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([@post], serializer: PostSerializer).to_a
refute serializers.first.custom_options.key?(:serializer) refute serializers.first.custom_options.key?(:serializer)
end end

View File

@ -8,7 +8,7 @@ class Model < ActiveModelSerializers::Model
# Convenience when not adding @attributes readers and writers # Convenience when not adding @attributes readers and writers
def method_missing(meth, *args) def method_missing(meth, *args)
if meth.to_s =~ /^(.*)=$/ if meth.to_s =~ /^(.*)=$/
attributes[$1.to_sym] = args[0] attributes[Regexp.last_match(1).to_sym] = args[0]
elsif attributes.key?(meth) elsif attributes.key?(meth)
attributes[meth] attributes[meth]
else else
@ -64,7 +64,7 @@ VirtualValue = Class.new(Model)
Comment = Class.new(Model) do Comment = Class.new(Model) do
# Uses a custom non-time-based cache key # Uses a custom non-time-based cache key
def cache_key def cache_key
"#{self.class.name.downcase}/#{self.id}" "#{self.class.name.downcase}/#{id}"
end end
end end

View File

@ -5,172 +5,174 @@ require 'kaminari'
require 'kaminari/hooks' require 'kaminari/hooks'
::Kaminari::Hooks.init ::Kaminari::Hooks.init
class ActiveModelSerializers::GrapeTest < ActiveSupport::TestCase module ActiveModelSerializers
include Rack::Test::Methods class GrapeTest < ActiveSupport::TestCase
module Models include Rack::Test::Methods
def self.model1 module Models
ARModels::Post.new(id: 1, title: 'Dummy Title', body: 'Lorem Ipsum') def self.model1
end ARModels::Post.new(id: 1, title: 'Dummy Title', body: 'Lorem Ipsum')
end
def self.model2 def self.model2
ARModels::Post.new(id: 2, title: 'Second Dummy Title', body: 'Second Lorem Ipsum') ARModels::Post.new(id: 2, title: 'Second Dummy Title', body: 'Second Lorem Ipsum')
end end
def self.all def self.all
@all ||= @all ||=
begin begin
model1.save! model1.save!
model2.save! model2.save!
ARModels::Post.all ARModels::Post.all
end end
end end
def self.reset_all def self.reset_all
ARModels::Post.delete_all ARModels::Post.delete_all
@all = nil @all = nil
end end
def self.collection_per def self.collection_per
2 2
end end
def self.collection def self.collection
@collection ||= @collection ||=
begin begin
Kaminari.paginate_array( Kaminari.paginate_array(
[ [
Profile.new(id: 1, name: 'Name 1', description: 'Description 1', comments: 'Comments 1'), Profile.new(id: 1, name: 'Name 1', description: 'Description 1', comments: 'Comments 1'),
Profile.new(id: 2, name: 'Name 2', description: 'Description 2', comments: 'Comments 2'), Profile.new(id: 2, name: 'Name 2', description: 'Description 2', comments: 'Comments 2'),
Profile.new(id: 3, name: 'Name 3', description: 'Description 3', comments: 'Comments 3'), Profile.new(id: 3, name: 'Name 3', description: 'Description 3', comments: 'Comments 3'),
Profile.new(id: 4, name: 'Name 4', description: 'Description 4', comments: 'Comments 4'), Profile.new(id: 4, name: 'Name 4', description: 'Description 4', comments: 'Comments 4'),
Profile.new(id: 5, name: 'Name 5', description: 'Description 5', comments: 'Comments 5') Profile.new(id: 5, name: 'Name 5', description: 'Description 5', comments: 'Comments 5')
] ]
).page(1).per(collection_per) ).page(1).per(collection_per)
end
end
end
class GrapeTest < Grape::API
format :json
include Grape::ActiveModelSerializers
resources :grape do
get '/render' do
render Models.model1
end end
end
end
class GrapeTest < Grape::API get '/render_with_json_api' do
format :json post = Models.model1
include Grape::ActiveModelSerializers render post, meta: { page: 1, total_pages: 2 }, adapter: :json_api
end
resources :grape do get '/render_array_with_json_api' do
get '/render' do posts = Models.all
render Models.model1 render posts, adapter: :json_api
end end
get '/render_with_json_api' do get '/render_collection_with_json_api' do
post = Models.model1 posts = Models.collection
render post, meta: { page: 1, total_pages: 2 }, adapter: :json_api render posts, adapter: :json_api
end end
get '/render_array_with_json_api' do get '/render_with_implicit_formatter' do
posts = Models.all Models.model1
render posts, adapter: :json_api end
end
get '/render_collection_with_json_api' do get '/render_array_with_implicit_formatter' do
posts = Models.collection Models.all
render posts, adapter: :json_api end
end
get '/render_with_implicit_formatter' do get '/render_collection_with_implicit_formatter' do
Models.model1 Models.collection
end end
get '/render_array_with_implicit_formatter' do
Models.all
end
get '/render_collection_with_implicit_formatter' do
Models.collection
end end
end end
end
def app def app
Grape::Middleware::Globals.new(GrapeTest.new) Grape::Middleware::Globals.new(GrapeTest.new)
end
def test_formatter_returns_json
get '/grape/render'
post = Models.model1
serializable_resource = serializable(post)
assert last_response.ok?
assert_equal serializable_resource.to_json, last_response.body
end
def test_render_helper_passes_through_options_correctly
get '/grape/render_with_json_api'
post = Models.model1
serializable_resource = serializable(post, serializer: ARModels::PostSerializer, adapter: :json_api, meta: { page: 1, total_pages: 2 })
assert last_response.ok?
assert_equal serializable_resource.to_json, last_response.body
end
def test_formatter_handles_arrays
get '/grape/render_array_with_json_api'
posts = Models.all
serializable_resource = serializable(posts, adapter: :json_api)
assert last_response.ok?
assert_equal serializable_resource.to_json, last_response.body
ensure
Models.reset_all
end
def test_formatter_handles_collections
get '/grape/render_collection_with_json_api'
assert last_response.ok?
representation = JSON.parse(last_response.body)
assert representation.include?('data')
assert representation['data'].count == Models.collection_per
assert representation.include?('links')
assert representation['links'].count > 0
end
def test_implicit_formatter
post = Models.model1
serializable_resource = serializable(post, adapter: :json_api)
with_adapter :json_api do
get '/grape/render_with_implicit_formatter'
end end
assert last_response.ok? def test_formatter_returns_json
assert_equal serializable_resource.to_json, last_response.body get '/grape/render'
end
def test_implicit_formatter_handles_arrays post = Models.model1
posts = Models.all serializable_resource = serializable(post)
serializable_resource = serializable(posts, adapter: :json_api)
with_adapter :json_api do assert last_response.ok?
get '/grape/render_array_with_implicit_formatter' assert_equal serializable_resource.to_json, last_response.body
end end
assert last_response.ok? def test_render_helper_passes_through_options_correctly
assert_equal serializable_resource.to_json, last_response.body get '/grape/render_with_json_api'
ensure
Models.reset_all
end
def test_implicit_formatter_handles_collections post = Models.model1
with_adapter :json_api do serializable_resource = serializable(post, serializer: ARModels::PostSerializer, adapter: :json_api, meta: { page: 1, total_pages: 2 })
get '/grape/render_collection_with_implicit_formatter'
assert last_response.ok?
assert_equal serializable_resource.to_json, last_response.body
end end
representation = JSON.parse(last_response.body) def test_formatter_handles_arrays
assert last_response.ok? get '/grape/render_array_with_json_api'
assert representation.include?('data')
assert representation['data'].count == Models.collection_per posts = Models.all
assert representation.include?('links') serializable_resource = serializable(posts, adapter: :json_api)
assert representation['links'].count > 0
assert last_response.ok?
assert_equal serializable_resource.to_json, last_response.body
ensure
Models.reset_all
end
def test_formatter_handles_collections
get '/grape/render_collection_with_json_api'
assert last_response.ok?
representation = JSON.parse(last_response.body)
assert representation.include?('data')
assert representation['data'].count == Models.collection_per
assert representation.include?('links')
assert representation['links'].count > 0
end
def test_implicit_formatter
post = Models.model1
serializable_resource = serializable(post, adapter: :json_api)
with_adapter :json_api do
get '/grape/render_with_implicit_formatter'
end
assert last_response.ok?
assert_equal serializable_resource.to_json, last_response.body
end
def test_implicit_formatter_handles_arrays
posts = Models.all
serializable_resource = serializable(posts, adapter: :json_api)
with_adapter :json_api do
get '/grape/render_array_with_implicit_formatter'
end
assert last_response.ok?
assert_equal serializable_resource.to_json, last_response.body
ensure
Models.reset_all
end
def test_implicit_formatter_handles_collections
with_adapter :json_api do
get '/grape/render_collection_with_implicit_formatter'
end
representation = JSON.parse(last_response.body)
assert last_response.ok?
assert representation.include?('data')
assert representation['data'].count == Models.collection_per
assert representation.include?('links')
assert representation['links'].count > 0
end
end end
end end

View File

@ -30,7 +30,7 @@ module ActiveModel
def errors def errors
end end
def self.human_attribute_name(attr, options = {}) def self.human_attribute_name(_, _ = {})
end end
def self.lookup_ancestors def self.lookup_ancestors

View File

@ -1,18 +1,20 @@
require 'test_helper' require 'test_helper'
class ActiveModelSerializers::LoggerTest < ActiveSupport::TestCase module ActiveModelSerializers
def test_logger_is_set_to_action_controller_logger_when_initializer_runs class LoggerTest < ActiveSupport::TestCase
assert_equal $action_controller_logger, ActionController::Base.logger # rubocop:disable Style/GlobalVars def test_logger_is_set_to_action_controller_logger_when_initializer_runs
end assert_equal $action_controller_logger, ActionController::Base.logger # rubocop:disable Style/GlobalVars
end
def test_logger_can_be_set def test_logger_can_be_set
original_logger = ActiveModelSerializers.logger original_logger = ActiveModelSerializers.logger
logger = Logger.new(STDOUT) logger = Logger.new(STDOUT)
ActiveModelSerializers.logger = logger ActiveModelSerializers.logger = logger
assert_equal ActiveModelSerializers.logger, logger assert_equal ActiveModelSerializers.logger, logger
ensure ensure
ActiveModelSerializers.logger = original_logger ActiveModelSerializers.logger = original_logger
end
end end
end end

View File

@ -3,7 +3,7 @@ require 'test_helper'
module ActiveModelSerializers module ActiveModelSerializers
class SerializableResourceTest < ActiveSupport::TestCase class SerializableResourceTest < ActiveSupport::TestCase
def setup def setup
@resource = Profile.new({ name: 'Name 1', description: 'Description 1', comments: 'Comments 1' }) @resource = Profile.new(name: 'Name 1', description: 'Description 1', comments: 'Comments 1')
@serializer = ProfileSerializer.new(@resource) @serializer = ProfileSerializer.new(@resource)
@adapter = ActiveModelSerializers::Adapter.create(@serializer) @adapter = ActiveModelSerializers::Adapter.create(@serializer)
@serializable_resource = SerializableResource.new(@resource) @serializable_resource = SerializableResource.new(@resource)
@ -32,11 +32,11 @@ module ActiveModelSerializers
end end
def test_use_adapter_with_adapter_option def test_use_adapter_with_adapter_option
assert SerializableResource.new(@resource, { adapter: 'json' }).use_adapter? assert SerializableResource.new(@resource, adapter: 'json').use_adapter?
end end
def test_use_adapter_with_adapter_option_as_false def test_use_adapter_with_adapter_option_as_false
refute SerializableResource.new(@resource, { adapter: false }).use_adapter? refute SerializableResource.new(@resource, adapter: false).use_adapter?
end end
class SerializableResourceErrorsTest < Minitest::Test class SerializableResourceErrorsTest < Minitest::Test
@ -45,14 +45,12 @@ module ActiveModelSerializers
resource = ModelWithErrors.new resource = ModelWithErrors.new
resource.errors.add(:name, 'must be awesome') resource.errors.add(:name, 'must be awesome')
serializable_resource = ActiveModelSerializers::SerializableResource.new( serializable_resource = ActiveModelSerializers::SerializableResource.new(
resource, { resource, serializer: ActiveModel::Serializer::ErrorSerializer,
serializer: ActiveModel::Serializer::ErrorSerializer, adapter: :json_api
adapter: :json_api
}
) )
expected_response_document = { expected_response_document = {
:errors => [ errors: [
{ :source => { :pointer => '/data/attributes/name' }, :detail => 'must be awesome' } { source: { pointer: '/data/attributes/name' }, detail: 'must be awesome' }
] ]
} }
assert_equal serializable_resource.as_json(options), expected_response_document assert_equal serializable_resource.as_json(options), expected_response_document
@ -65,15 +63,13 @@ module ActiveModelSerializers
resource.errors.add(:title, 'must be amazing') resource.errors.add(:title, 'must be amazing')
resources << ModelWithErrors.new resources << ModelWithErrors.new
serializable_resource = SerializableResource.new( serializable_resource = SerializableResource.new(
resources, { resources, serializer: ActiveModel::Serializer::ErrorsSerializer,
serializer: ActiveModel::Serializer::ErrorsSerializer, each_serializer: ActiveModel::Serializer::ErrorSerializer,
each_serializer: ActiveModel::Serializer::ErrorSerializer, adapter: :json_api
adapter: :json_api
}
) )
expected_response_document = { expected_response_document = {
:errors => [ errors: [
{ :source => { :pointer => '/data/attributes/title' }, :detail => 'must be amazing' } { source: { pointer: '/data/attributes/title' }, detail: 'must be amazing' }
] ]
} }
assert_equal serializable_resource.as_json(options), expected_response_document assert_equal serializable_resource.as_json(options), expected_response_document

View File

@ -7,10 +7,10 @@ module ActiveModel
@author = Author.new(name: 'Steve K.') @author = Author.new(name: 'Steve K.')
@author.bio = nil @author.bio = nil
@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(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]
@post.blog = @blog @post.blog = @blog
@ -19,7 +19,7 @@ module ActiveModel
@post.author = @author @post.author = @author
@author.posts = [@post] @author.posts = [@post]
@post_serializer = PostSerializer.new(@post, { custom_options: true }) @post_serializer = PostSerializer.new(@post, custom_options: true)
@author_serializer = AuthorSerializer.new(@author) @author_serializer = AuthorSerializer.new(@author)
@comment_serializer = CommentSerializer.new(@comment) @comment_serializer = CommentSerializer.new(@comment)
end end
@ -143,12 +143,12 @@ module ActiveModel
) )
actual = serializable(post, adapter: :attributes, serializer: InlineAssociationTestPostSerializer).as_json actual = serializable(post, adapter: :attributes, serializer: InlineAssociationTestPostSerializer).as_json
expected = { expected = {
:comments => [ comments: [
{ :id => 1, :contents => 'first comment' }, { id: 1, contents: 'first comment' },
{ :id => 2, :contents => 'last comment' } { id: 2, contents: 'last comment' }
], ],
:last_comments => [ last_comments: [
{ :id => 2, :contents => 'last comment' } { id: 2, contents: 'last comment' }
] ]
} }

View File

@ -22,7 +22,7 @@ module ActiveModel
inherited_klass = Class.new(AlternateBlogSerializer) inherited_klass = Class.new(AlternateBlogSerializer)
blog_serializer = inherited_klass.new(@blog) blog_serializer = inherited_klass.new(@blog)
adapter = ActiveModelSerializers::Adapter::Attributes.new(blog_serializer) adapter = ActiveModelSerializers::Adapter::Attributes.new(blog_serializer)
assert_equal({ :id => 1, :title => 'AMS Hints' }, adapter.serializable_hash) assert_equal({ id: 1, title: 'AMS Hints' }, adapter.serializable_hash)
end end
def test_multiple_calls_with_the_same_attribute def test_multiple_calls_with_the_same_attribute

View File

@ -4,7 +4,7 @@ module ActiveModel
class Serializer class Serializer
class AttributesTest < ActiveSupport::TestCase class AttributesTest < ActiveSupport::TestCase
def setup def setup
@profile = Profile.new({ name: 'Name 1', description: 'Description 1', comments: 'Comments 1' }) @profile = Profile.new(name: 'Name 1', description: 'Description 1', comments: 'Comments 1')
@profile_serializer = ProfileSerializer.new(@profile) @profile_serializer = ProfileSerializer.new(@profile)
@comment = Comment.new(id: 1, body: 'ZOMG!!', date: '2015') @comment = Comment.new(id: 1, body: 'ZOMG!!', date: '2015')
@serializer_klass = Class.new(CommentSerializer) @serializer_klass = Class.new(CommentSerializer)

View File

@ -5,7 +5,7 @@ module ActiveModel
class FieldsetTest < ActiveSupport::TestCase class FieldsetTest < ActiveSupport::TestCase
def test_fieldset_with_hash def test_fieldset_with_hash
fieldset = ActiveModel::Serializer::Fieldset.new('post' => %w(id title), 'comment' => ['body']) fieldset = ActiveModel::Serializer::Fieldset.new('post' => %w(id title), 'comment' => ['body'])
expected = { :post => [:id, :title], :comment => [:body] } expected = { post: [:id, :title], comment: [:body] }
assert_equal(expected, fieldset.fields) assert_equal(expected, fieldset.fields)
end end

View File

@ -8,7 +8,7 @@ module ActiveModel
end end
def test_overwrite_root def test_overwrite_root
serializer = VirtualValueSerializer.new(@virtual_value, { root: 'smth' }) serializer = VirtualValueSerializer.new(@virtual_value, root: 'smth')
assert_equal('smth', serializer.json_key) assert_equal('smth', serializer.json_key)
end end

View File

@ -41,7 +41,9 @@ module ActiveModel
end end
class CustomProfile class CustomProfile
def serializer_class; ProfileSerializer; end def serializer_class
ProfileSerializer
end
end end
Tweet = Class.new(::Model) Tweet = Class.new(::Model)

View File

@ -75,6 +75,8 @@ module TestHelpers
end end
end end
class ActiveSupport::TestCase module ActiveSupport
include TestHelpers::Generation class TestCase
include TestHelpers::Generation
end
end end

View File

@ -44,10 +44,12 @@ module SerializationTesting
end end
end end
class Minitest::Test module Minitest
def before_setup class Test
ActionController::Base.cache_store.clear def before_setup
end ActionController::Base.cache_store.clear
end
include SerializationTesting include SerializationTesting
end
end end