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:
TargetRubyVersion: 2.2
TargetRubyVersion: 2.1
Exclude:
- config/initializers/forbidden_yaml.rb
- !ruby/regexp /(vendor|bundle|bin|db|tmp)\/.*/
@ -46,7 +44,7 @@ Style/AlignParameters:
EnforcedStyle: with_fixed_indentation
Style/ClassAndModuleChildren:
EnforcedStyle: compact
EnforcedStyle: nested
Style/Documentation:
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
begin
require 'simplecov'
rescue LoadError
rescue LoadError # rubocop:disable Lint/HandleExceptions
end
Bundler::GemHelper.install_tasks
@ -33,7 +33,7 @@ end
begin
require 'rubocop'
require 'rubocop/rake_task'
rescue LoadError
rescue LoadError # rubocop:disable Lint/HandleExceptions
else
Rake::Task[:rubocop].clear if Rake::Task.task_defined?(:rubocop)
require 'rbconfig'
@ -100,4 +100,4 @@ else
end
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']
spec.add_runtime_dependency 'activemodel', rails_versions
# 'activesupport', rails_versions
# 'builder'
# 'activesupport', rails_versions
# 'builder'
spec.add_runtime_dependency 'actionpack', rails_versions
# 'activesupport', rails_versions
# 'rack'
# 'rack-test', '~> 0.6.2'
# 'activesupport', rails_versions
# 'rack'
# 'rack-test', '~> 0.6.2'
spec.add_runtime_dependency 'railties', rails_versions
# 'activesupport', rails_versions
# 'actionpack', rails_versions
# 'rake', '>= 0.8.7'
# 'activesupport', rails_versions
# 'actionpack', rails_versions
# 'rake', '>= 0.8.7'
# 'activesupport', rails_versions
# 'i18n,
# 'tzinfo'
# 'minitest'
# 'thread_safe'
# 'i18n,
# 'tzinfo'
# 'minitest'
# 'thread_safe'
spec.add_runtime_dependency 'jsonapi', '~> 0.1.1.beta2'
spec.add_development_dependency 'activerecord', rails_versions
# arel
# activesupport
# activemodel
# arel
# activesupport
# activemodel
# Soft dependency for pagination
spec.add_development_dependency 'kaminari', ' ~> 0.16.3'

View File

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

View File

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

View File

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

View File

@ -39,7 +39,7 @@ module ActiveModel
# @example
# 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))
end
@ -61,7 +61,7 @@ module ActiveModel
# @example
# 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))
end

View File

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

View File

@ -1,27 +1,32 @@
require 'active_model/serializer/error_serializer'
class ActiveModel::Serializer::ErrorsSerializer
include Enumerable
delegate :each, to: :@serializers
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))
module ActiveModel
class Serializer
class ErrorsSerializer
include Enumerable
delegate :each, to: :@serializers
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
def success?
false
end
def json_key
nil
end
protected
attr_reader :serializers
end

View File

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

View File

@ -36,7 +36,7 @@ module ActiveModelSerializers
target = is_a?(Module) ? "#{self}." : "#{self.class}#"
msg = ["NOTE: #{target}#{name} is deprecated",
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}."
send old, *args, &block
end

View File

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

View File

@ -23,7 +23,7 @@ module ActiveModelSerializers
# 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
# 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.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.

View File

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

View File

@ -2,11 +2,11 @@ module Rails
module Generators
class SerializerGenerator < NamedBase
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
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/helpers/active_model_serializers'
module Grape::ActiveModelSerializers
extend ActiveSupport::Concern
module Grape
module ActiveModelSerializers
extend ActiveSupport::Concern
included do
formatter :json, Grape::Formatters::ActiveModelSerializers
helpers Grape::Helpers::ActiveModelSerializers
included do
formatter :json, Grape::Formatters::ActiveModelSerializers
helpers Grape::Helpers::ActiveModelSerializers
end
end
end

View File

@ -5,17 +5,17 @@ module ActionController
class AdapterSelectorTest < ActionController::TestCase
class AdapterSelectorTestController < ActionController::Base
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
end
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
end
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
end
end

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -17,7 +17,7 @@ module ActiveModelSerializers
@first_post = Post.new(id: 10, title: 'Hello!!', body: 'Hello, world!!')
@second_post = Post.new(id: 20, title: 'New 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')
@second_comment = Comment.new(id: 2, body: 'ZOMG ANOTHER COMMENT')
@first_post.blog = @blog

View File

@ -13,11 +13,11 @@ module ActiveModelSerializers
def setup
ActionController::Base.cache_store.clear
@array = [
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: 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: 5, name: 'Name 5', description: 'Description 5', comments: 'Comments 5' })
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: 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: 5, name: 'Name 5', description: 'Description 5', comments: 'Comments 5')
]
end
@ -122,7 +122,7 @@ module ActiveModelSerializers
end
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,
adapter.serializable_hash

View File

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

View File

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

View File

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

View File

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

View File

@ -4,7 +4,7 @@ module ActiveModelSerializers
module Adapter
class NullTest < ActiveSupport::TestCase
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)
@adapter = Null.new(serializer)
@ -20,4 +20,3 @@ module ActiveModelSerializers
end
end
end

View File

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

View File

@ -51,7 +51,7 @@ module ActiveModelSerializers
end
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
end

View File

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

View File

@ -101,7 +101,7 @@ module ActiveModelSerializers
uncached_author_serializer = AuthorSerializer.new(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}"
assert_equal(uncached_author_serializer.attributes.to_json, cache_store.fetch(key).to_json)
end

View File

@ -11,7 +11,7 @@ module ActiveModel
@comment = Comment.new
@post = Post.new
@resource = build_named_collection @comment, @post
@serializer = collection_serializer.new(@resource, { some: :options })
@serializer = collection_serializer.new(@resource, some: :options)
end
def collection_serializer
@ -44,7 +44,7 @@ module ActiveModel
end
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)
end

View File

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

View File

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

View File

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

View File

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

View File

@ -3,7 +3,7 @@ require 'test_helper'
module ActiveModelSerializers
class SerializableResourceTest < ActiveSupport::TestCase
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)
@adapter = ActiveModelSerializers::Adapter.create(@serializer)
@serializable_resource = SerializableResource.new(@resource)
@ -32,11 +32,11 @@ module ActiveModelSerializers
end
def test_use_adapter_with_adapter_option
assert SerializableResource.new(@resource, { adapter: 'json' }).use_adapter?
assert SerializableResource.new(@resource, adapter: 'json').use_adapter?
end
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
class SerializableResourceErrorsTest < Minitest::Test
@ -45,14 +45,12 @@ module ActiveModelSerializers
resource = ModelWithErrors.new
resource.errors.add(:name, 'must be awesome')
serializable_resource = ActiveModelSerializers::SerializableResource.new(
resource, {
serializer: ActiveModel::Serializer::ErrorSerializer,
adapter: :json_api
}
resource, serializer: ActiveModel::Serializer::ErrorSerializer,
adapter: :json_api
)
expected_response_document = {
:errors => [
{ :source => { :pointer => '/data/attributes/name' }, :detail => 'must be awesome' }
errors: [
{ source: { pointer: '/data/attributes/name' }, detail: 'must be awesome' }
]
}
assert_equal serializable_resource.as_json(options), expected_response_document
@ -65,15 +63,13 @@ module ActiveModelSerializers
resource.errors.add(:title, 'must be amazing')
resources << ModelWithErrors.new
serializable_resource = SerializableResource.new(
resources, {
serializer: ActiveModel::Serializer::ErrorsSerializer,
each_serializer: ActiveModel::Serializer::ErrorSerializer,
adapter: :json_api
}
resources, serializer: ActiveModel::Serializer::ErrorsSerializer,
each_serializer: ActiveModel::Serializer::ErrorSerializer,
adapter: :json_api
)
expected_response_document = {
:errors => [
{ :source => { :pointer => '/data/attributes/title' }, :detail => 'must be amazing' }
errors: [
{ source: { pointer: '/data/attributes/title' }, detail: 'must be amazing' }
]
}
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.bio = nil
@author.roles = []
@blog = Blog.new({ name: 'AMS Blog' })
@post = Post.new({ title: 'New Post', body: 'Body' })
@tag = Tag.new({ name: '#hashtagged' })
@comment = Comment.new({ id: 1, body: 'ZOMG A COMMENT' })
@blog = Blog.new(name: 'AMS Blog')
@post = Post.new(title: 'New Post', body: 'Body')
@tag = Tag.new(name: '#hashtagged')
@comment = Comment.new(id: 1, body: 'ZOMG A COMMENT')
@post.comments = [@comment]
@post.tags = [@tag]
@post.blog = @blog
@ -19,7 +19,7 @@ module ActiveModel
@post.author = @author
@author.posts = [@post]
@post_serializer = PostSerializer.new(@post, { custom_options: true })
@post_serializer = PostSerializer.new(@post, custom_options: true)
@author_serializer = AuthorSerializer.new(@author)
@comment_serializer = CommentSerializer.new(@comment)
end
@ -143,12 +143,12 @@ module ActiveModel
)
actual = serializable(post, adapter: :attributes, serializer: InlineAssociationTestPostSerializer).as_json
expected = {
:comments => [
{ :id => 1, :contents => 'first comment' },
{ :id => 2, :contents => 'last comment' }
comments: [
{ id: 1, contents: 'first comment' },
{ id: 2, contents: 'last comment' }
],
:last_comments => [
{ :id => 2, :contents => 'last comment' }
last_comments: [
{ id: 2, contents: 'last comment' }
]
}

View File

@ -22,7 +22,7 @@ module ActiveModel
inherited_klass = Class.new(AlternateBlogSerializer)
blog_serializer = inherited_klass.new(@blog)
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
def test_multiple_calls_with_the_same_attribute

View File

@ -4,7 +4,7 @@ module ActiveModel
class Serializer
class AttributesTest < ActiveSupport::TestCase
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)
@comment = Comment.new(id: 1, body: 'ZOMG!!', date: '2015')
@serializer_klass = Class.new(CommentSerializer)

View File

@ -5,7 +5,7 @@ module ActiveModel
class FieldsetTest < ActiveSupport::TestCase
def test_fieldset_with_hash
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)
end

View File

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

View File

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

View File

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

View File

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