Merge remote-tracking branch 'upstream/master' into fix-jsonapi-ri

This commit is contained in:
Lucas Hosseini 2015-09-06 17:21:43 +02:00
commit 070a2e63bd
65 changed files with 1013 additions and 532 deletions

49
.rubocop.yml Normal file
View File

@ -0,0 +1,49 @@
inherit_from: .rubocop_todo.yml
AllCops:
Exclude:
- config/initializers/forbidden_yaml.rb
- !ruby/regexp /(vendor|bundle|bin|db|tmp)\/.*/
RunRailsCops: true
DisplayCopNames: true
DisplayStyleGuide: true
Lint/NestedMethodDefinition:
Enabled: false
Exclude:
- test/action_controller/serialization_test.rb
Style/StringLiterals:
EnforcedStyle: single_quotes
Metrics/AbcSize:
Max: 35 # TODO: Lower to 15
Metrics/ClassLength:
Max: 261 # TODO: Lower to 100
Exclude:
- test/**/*.rb
Metrics/CyclomaticComplexity:
Max: 7 # TODO: Lower to 6
Metrics/LineLength:
Max: 251 # TODO: Lower to 80
Metrics/MethodLength:
Max: 106 # TODO: Lower to 10
Metrics/PerceivedComplexity:
Max: 9 # TODO: Lower to 7
Style/AlignParameters:
EnforcedStyle: with_fixed_indentation
Style/ClassAndModuleChildren:
EnforcedStyle: compact
Style/Documentation:
Enabled: false
Style/MultilineOperationIndentation:
EnforcedStyle: indented

315
.rubocop_todo.yml Normal file
View File

@ -0,0 +1,315 @@
# This configuration was generated by
# `rubocop --auto-gen-config`
# on 2015-08-31 04:23:33 -0500 using RuboCop version 0.33.0.
# 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: 1
# Configuration parameters: AllowSafeAssignment.
Lint/AssignmentInCondition:
Exclude:
- 'lib/active_model/serializer/adapter/json_api.rb'
# Offense count: 1
Lint/EmptyEnsure:
Exclude:
- 'test/serializers/adapter_for_test.rb'
# Offense count: 1
Lint/HandleExceptions:
Exclude:
- 'Rakefile'
# Offense count: 2
# Cop supports --auto-correct.
Lint/UnusedBlockArgument:
Exclude:
- 'lib/active_model/serializer/adapter/json_api/fragment_cache.rb'
# Offense count: 9
# Cop supports --auto-correct.
Lint/UnusedMethodArgument:
Exclude:
- 'lib/active_model/serializer/adapter.rb'
- 'lib/active_model/serializer/adapter/null.rb'
- 'lib/active_model/serializer/pass_through_serializer.rb'
- 'test/fixtures/poro.rb'
- 'test/lint_test.rb'
# Offense count: 1
Lint/UselessAccessModifier:
Exclude:
- 'lib/active_model/serializable_resource.rb'
# Offense count: 3
Lint/UselessAssignment:
Exclude:
- 'bench/perf.rb'
- 'lib/active_model/serializer/adapter/json_api/fragment_cache.rb'
- 'test/test_helper.rb'
# Offense count: 1
# Configuration parameters: EnforcedStyle, SupportedStyles.
Rails/Date:
Exclude:
- 'test/fixtures/poro.rb'
# Offense count: 8
# Configuration parameters: EnforcedStyle, SupportedStyles.
Rails/TimeZone:
Exclude:
- 'test/action_controller/serialization_test.rb'
- 'test/fixtures/poro.rb'
- 'test/serializers/cache_test.rb'
# Offense count: 16
# Cop supports --auto-correct.
# Configuration parameters: EnforcedHashRocketStyle, EnforcedColonStyle, EnforcedLastArgumentHashStyle, SupportedLastArgumentHashStyles.
Style/AlignHash:
Exclude:
- 'test/action_controller/json_api/pagination_test.rb'
# Offense count: 1
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles.
Style/AndOr:
Exclude:
- 'lib/active_model/serializer/lint.rb'
# Offense count: 6
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles, ProceduralMethods, FunctionalMethods, IgnoredMethods.
Style/BlockDelimiters:
Enabled: false
# Offense count: 46
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles.
Style/BracesAroundHashParameters:
Exclude:
- 'test/action_controller/adapter_selector_test.rb'
- 'test/action_controller/json_api/pagination_test.rb'
- 'test/action_controller/serialization_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/array_serializer_test.rb'
- 'test/serializable_resource_test.rb'
- 'test/serializers/associations_test.rb'
- 'test/serializers/attribute_test.rb'
- 'test/serializers/attributes_test.rb'
- 'test/serializers/fieldset_test.rb'
- 'test/serializers/root_test.rb'
- 'test/serializers/urls_test.rb'
# Offense count: 167
# Configuration parameters: EnforcedStyle, SupportedStyles.
Style/ClassAndModuleChildren:
Enabled: false
# Offense count: 5
# 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
Style/EachWithObject:
Exclude:
- 'lib/active_model/serializer/fieldset.rb'
# Offense count: 3
# Configuration parameters: MinBodyLength.
Style/GuardClause:
Exclude:
- 'lib/active_model/serializer.rb'
- 'lib/active_model/serializer/adapter/json_api.rb'
- 'test/capture_warnings.rb'
# Offense count: 12
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles, UseHashRocketsWithSymbolValues.
Style/HashSyntax:
Enabled: false
# Offense count: 9
# Cop supports --auto-correct.
Style/IndentArray:
Exclude:
- 'test/adapter/json/has_many_test.rb'
- 'test/adapter/json_api/json_api_test.rb'
- 'test/adapter/json_api/pagination_links_test.rb'
- 'test/adapter/json_test.rb'
# Offense count: 8
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles.
Style/IndentHash:
Enabled: false
# Offense count: 1
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles.
Style/IndentationConsistency:
Exclude:
- 'test/action_controller/serialization_scope_name_test.rb'
# Offense count: 2
# Cop supports --auto-correct.
# Configuration parameters: Width.
Style/IndentationWidth:
Exclude:
- 'lib/active_model/serializable_resource.rb'
- 'lib/active_model/serializer/fieldset.rb'
# Offense count: 1
# Cop supports --auto-correct.
Style/Lambda:
Exclude:
- 'lib/active_model/serializer.rb'
# Offense count: 2
# Cop supports --auto-correct.
Style/MethodCallParentheses:
Exclude:
- 'lib/active_model/serializer/adapter/json.rb'
- 'lib/active_model/serializer/adapter/json_api.rb'
# Offense count: 1
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles.
Style/MethodDefParentheses:
Enabled: false
# Offense count: 3
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles.
Style/MultilineOperationIndentation:
Enabled: false
# Offense count: 1
# Cop supports --auto-correct.
Style/NegatedIf:
Exclude:
- 'lib/action_controller/serialization.rb'
# Offense count: 1
# Configuration parameters: EnforcedStyle, MinBodyLength, SupportedStyles.
Style/Next:
Exclude:
- 'lib/active_model/serializer/adapter/json_api.rb'
# Offense count: 1
# Cop supports --auto-correct.
Style/NumericLiterals:
MinDigits: 7
# Offense count: 2
# Cop supports --auto-correct.
# Configuration parameters: PreferredDelimiters.
Style/PercentLiteralDelimiters:
Exclude:
- 'active_model_serializers.gemspec'
# Offense count: 2
# Cop supports --auto-correct.
Style/PerlBackrefs:
Exclude:
- 'test/fixtures/poro.rb'
- 'test/serializers/associations_test.rb'
# Offense count: 6
# Configuration parameters: NamePrefix, NamePrefixBlacklist.
Style/PredicateName:
Exclude:
- 'lib/active_model/serializer/adapter.rb'
- 'lib/active_model/serializer/adapter/json_api.rb'
- 'lib/active_model/serializer/associations.rb'
- 'test/action_controller/json_api/linked_test.rb'
# Offense count: 7
# Cop supports --auto-correct.
Style/RedundantSelf:
Exclude:
- 'lib/active_model/serializer.rb'
- 'lib/active_model/serializer/associations.rb'
- 'test/fixtures/poro.rb'
# Offense count: 1
# Cop supports --auto-correct.
# Configuration parameters: AllowAsExpressionSeparator.
Style/Semicolon:
Exclude:
- 'lib/active_model/serializer/fieldset.rb'
# Offense count: 6
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles.
Style/SignalException:
Exclude:
- 'lib/active_model/serializer.rb'
- 'lib/active_model/serializer/adapter.rb'
- 'lib/active_model/serializer/fieldset.rb'
- 'lib/active_model/serializer/pass_through_serializer.rb'
# Offense count: 1
# Cop supports --auto-correct.
# Configuration parameters: AllowIfMethodIsEmpty.
Style/SingleLineMethods:
Exclude:
- 'test/serializers/serializer_for_test.rb'
# Offense count: 2
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles.
Style/StringLiteralsInInterpolation:
Enabled: false
# Offense count: 1
Style/StructInheritance:
Exclude:
- 'bench/perf.rb'
# Offense count: 1
# Cop supports --auto-correct.
# Configuration parameters: IgnoredMethods.
Style/SymbolProc:
Exclude:
- 'lib/generators/serializer/serializer_generator.rb'
# Offense count: 8
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles.
Style/TrailingBlankLines:
Exclude:
- 'lib/active_model/serializer/pass_through_serializer.rb'
- 'lib/generators/serializer/serializer_generator.rb'
- 'test/adapter/fragment_cache_test.rb'
- 'test/adapter/json_api/json_api_test.rb'
- 'test/adapter/null_test.rb'
- 'test/serializers/cache_test.rb'
- 'test/serializers/fieldset_test.rb'
- 'test/support/stream_capture.rb'
# Offense count: 6
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyleForMultiline, SupportedStyles.
Style/TrailingComma:
Exclude:
- 'test/action_controller/adapter_selector_test.rb'
- 'test/action_controller/serialization_test.rb'
- 'test/adapter/json_api/belongs_to_test.rb'
- 'test/adapter/json_api/linked_test.rb'
# Offense count: 1
Style/UnlessElse:
Exclude:
- 'lib/active_model/serializer.rb'

View File

@ -2,6 +2,9 @@ language: ruby
sudo: false sudo: false
cache:
bundler: true
rvm: rvm:
- 1.9.3 - 1.9.3
- 2.0.0 - 2.0.0
@ -14,6 +17,10 @@ rvm:
install: install:
- bundle install --retry=3 - bundle install --retry=3
script:
- bundle exec rake
- bundle exec rake rubocop
env: env:
- "RAILS_VERSION=4.0" - "RAILS_VERSION=4.0"
- "RAILS_VERSION=4.1" - "RAILS_VERSION=4.1"
@ -24,3 +31,4 @@ matrix:
allow_failures: allow_failures:
- rvm: ruby-head - rvm: ruby-head
- env: "RAILS_VERSION=master" - env: "RAILS_VERSION=master"
fast_finish: true

37
Gemfile
View File

@ -3,18 +3,37 @@ source 'https://rubygems.org'
# Specify your gem's dependencies in active_model_serializers.gemspec # Specify your gem's dependencies in active_model_serializers.gemspec
gemspec gemspec
gem "minitest" version = ENV['RAILS_VERSION'] || '4.2'
version = ENV["RAILS_VERSION"] || "4.2" if version == 'master'
gem 'rack', github: 'rack/rack'
if version == "master" git 'https://github.com/rails/rails.git' do
gem "rails", github: "rails/rails" gem 'railties'
gem 'activesupport'
# ugh https://github.com/rails/rails/issues/16063#issuecomment-48090125 gem 'activemodel'
gem "arel", github: "rails/arel" gem 'actionpack'
# Rails 5
gem 'actionview'
end
# Rails 5
gem 'rails-controller-testing', github: 'rails/rails-controller-testing'
else else
gem "rails", "~> #{version}.0" gem_version = "~> #{version}.0"
gem 'railties', gem_version
gem 'activesupport', gem_version
gem 'activemodel', gem_version
gem 'actionpack', gem_version
end
group :test do
gem 'activerecord'
gem 'sqlite3', platform: :ruby
gem 'activerecord-jdbcsqlite3-adapter', platform: :jruby
end end
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem # Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby] gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
group :development, :test do
gem 'rubocop', '~> 0.33.0', require: false
end

View File

@ -1,9 +1,31 @@
require "bundler/gem_tasks" require 'bundler/gem_tasks'
begin
require 'rubocop'
require 'rubocop/rake_task'
rescue LoadError
else
Rake::Task[:rubocop].clear if Rake::Task.task_defined?(:rubocop)
if !defined?(::Rubinius)
Rake::Task[:rubocop].clear if Rake::Task.task_defined?(:rubocop)
desc 'Execute rubocop'
RuboCop::RakeTask.new(:rubocop) do |task|
task.options = ['--rails', '--display-cop-names', '--display-style-guide']
task.fail_on_error = true
end
else
desc 'No-op rubocop to avoid rbx segfault'
task :rubocop do
puts 'Skipping rubocop on rbx due to segfault'
puts 'https://github.com/rubinius/rubinius/issues/3499'
end
end
end
require 'rake/testtask' require 'rake/testtask'
Rake::TestTask.new do |t| Rake::TestTask.new do |t|
t.libs << "test" t.libs << 'test'
t.test_files = FileList['test/**/*_test.rb'] t.test_files = FileList['test/**/*_test.rb']
t.ruby_opts = ['-r./test/test_helper.rb'] t.ruby_opts = ['-r./test/test_helper.rb']
t.verbose = true t.verbose = true

View File

@ -4,26 +4,47 @@ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'active_model/serializer/version' require 'active_model/serializer/version'
Gem::Specification.new do |spec| Gem::Specification.new do |spec|
spec.name = "active_model_serializers" spec.name = 'active_model_serializers'
spec.version = ActiveModel::Serializer::VERSION spec.version = ActiveModel::Serializer::VERSION
spec.authors = ["Steve Klabnik"] spec.platform = Gem::Platform::RUBY
spec.email = ["steve@steveklabnik.com"] spec.authors = ['Steve Klabnik']
spec.summary = %q{Conventions-based JSON generation for Rails.} spec.email = ['steve@steveklabnik.com']
spec.description = %q{ActiveModel::Serializers allows you to generate your JSON in an object-oriented and convention-driven manner.} spec.summary = 'Conventions-based JSON generation for Rails.'
spec.homepage = "https://github.com/rails-api/active_model_serializers" spec.description = 'ActiveModel::Serializers allows you to generate your JSON in an object-oriented and convention-driven manner.'
spec.license = "MIT" spec.homepage = 'https://github.com/rails-api/active_model_serializers'
spec.license = 'MIT'
spec.files = `git ls-files -z`.split("\x0") spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"] spec.require_paths = ['lib']
spec.add_dependency "activemodel", ">= 4.0" spec.required_ruby_version = '>= 1.9.3'
spec.add_development_dependency "rails", ">= 4.0" rails_versions = '>= 4.0'
spec.add_development_dependency "bundler", "~> 1.6" spec.add_runtime_dependency 'activemodel', rails_versions
spec.add_development_dependency "timecop", ">= 0.7" # 'activesupport', rails_versions
spec.add_development_dependency "rake" # 'builder'
spec.add_development_dependency "kaminari"
spec.add_development_dependency "will_paginate" spec.add_runtime_dependency 'actionpack', rails_versions
# '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
# 'i18n,
# 'tzinfo'
# 'minitest'
# 'thread_safe'
# Soft dependency for pagination
spec.add_development_dependency 'kaminari'
spec.add_development_dependency 'will_paginate'
spec.add_development_dependency 'bundler', '~> 1.6'
spec.add_development_dependency 'timecop', '>= 0.7'
end end

View File

@ -21,7 +21,7 @@ module ActionController
def get_serializer(resource, options = {}) def get_serializer(resource, options = {})
if !use_adapter? if !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#serialize" "Please pass 'adapter: false' or see ActiveSupport::SerializableResource#serialize"
options[:adapter] = false options[:adapter] = false
end end

View File

@ -1,7 +1,6 @@
require 'set' require 'set'
module ActiveModel module ActiveModel
class SerializableResource class SerializableResource
ADAPTER_OPTION_KEYS = Set.new([:include, :fields, :adapter]) ADAPTER_OPTION_KEYS = Set.new([:include, :fields, :adapter])
def initialize(resource, options = {}) def initialize(resource, options = {})
@ -79,6 +78,5 @@ module ActiveModel
ActiveModelSerializers.silence_warnings do ActiveModelSerializers.silence_warnings do
attr_reader :resource, :adapter_opts, :serializer_opts attr_reader :resource, :adapter_opts, :serializer_opts
end end
end end
end end

View File

@ -13,7 +13,6 @@ module ActiveModel
include Configuration include Configuration
include Associations include Associations
# Matches # Matches
# "c:/git/emberjs/ember-crm-backend/app/serializers/lead_serializer.rb:1:in `<top (required)>'" # "c:/git/emberjs/ember-crm-backend/app/serializers/lead_serializer.rb:1:in `<top (required)>'"
# AND # AND
@ -70,7 +69,7 @@ module ActiveModel
ActiveModelSerializers.silence_warnings do ActiveModelSerializers.silence_warnings do
define_method key do define_method key do
object.read_attribute_for_serialization(attr) object.read_attribute_for_serialization(attr)
end unless respond_to?(key, false) || _fragmented.respond_to?(attr) end unless (key != :id && method_defined?(key)) || _fragmented.respond_to?(attr)
end end
end end

View File

@ -15,7 +15,7 @@ module ActiveModel
end end
def self.adapter_class(adapter) def self.adapter_class(adapter)
adapter_name = adapter.to_s.classify.sub("API", "Api") adapter_name = adapter.to_s.classify.sub('API', 'Api')
"ActiveModel::Serializer::Adapter::#{adapter_name}".safe_constantize "ActiveModel::Serializer::Adapter::#{adapter_name}".safe_constantize
end end
@ -68,12 +68,12 @@ module ActiveModel
parts = [] parts = []
parts << object_cache_key parts << object_cache_key
parts << @klass._cache_digest unless @klass._cache_options && @klass._cache_options[:skip_digest] parts << @klass._cache_digest unless @klass._cache_options && @klass._cache_options[:skip_digest]
parts.join("/") parts.join('/')
end end
def object_cache_key def object_cache_key
object_time_safe = @cached_serializer.object.updated_at object_time_safe = @cached_serializer.object.updated_at
object_time_safe = object_time_safe.strftime("%Y%m%d%H%M%S%9N") if object_time_safe.respond_to?(:strftime) object_time_safe = object_time_safe.strftime('%Y%m%d%H%M%S%9N') if object_time_safe.respond_to?(:strftime)
(@klass._cache_key) ? "#{@klass._cache_key}/#{@cached_serializer.object.id}-#{object_time_safe}" : @cached_serializer.object.cache_key (@klass._cache_key) ? "#{@klass._cache_key}/#{@cached_serializer.object.id}-#{object_time_safe}" : @cached_serializer.object.cache_key
end end
@ -82,7 +82,7 @@ module ActiveModel
end end
def meta_key def meta_key
serializer.meta_key || "meta" serializer.meta_key || 'meta'
end end
def root def root

View File

@ -2,7 +2,6 @@ module ActiveModel
class Serializer class Serializer
class Adapter class Adapter
class FragmentCache class FragmentCache
attr_reader :serializer attr_reader :serializer
def initialize(adapter, serializer, options) def initialize(adapter, serializer, options)

View File

@ -46,7 +46,6 @@ module ActiveModel
def fragment_cache(cached_hash, non_cached_hash) def fragment_cache(cached_hash, non_cached_hash)
Json::FragmentCache.new().fragment_cache(cached_hash, non_cached_hash) Json::FragmentCache.new().fragment_cache(cached_hash, non_cached_hash)
end end
end end
end end
end end

View File

@ -4,11 +4,9 @@ module ActiveModel
class Adapter class Adapter
class Json < Adapter class Json < Adapter
class FragmentCache class FragmentCache
def fragment_cache(cached_hash, non_cached_hash) def fragment_cache(cached_hash, non_cached_hash)
non_cached_hash.merge cached_hash non_cached_hash.merge cached_hash
end end
end end
end end
end end

View File

@ -159,19 +159,21 @@ module ActiveModel
def add_links(options) def add_links(options)
links = @hash.fetch(:links) { {} } links = @hash.fetch(:links) { {} }
resources = serializer.instance_variable_get(:@resource) collection = serializer.object
@hash[:links] = add_pagination_links(links, resources, options) if is_paginated?(resources) if is_paginated?(collection)
@hash[:links] = add_pagination_links(links, collection, options)
end
end end
def add_pagination_links(links, resources, options) def add_pagination_links(links, collection, options)
pagination_links = JsonApi::PaginationLinks.new(resources, options[:context]).serializable_hash(options) pagination_links = JsonApi::PaginationLinks.new(collection, options[:context]).serializable_hash(options)
links.update(pagination_links) links.update(pagination_links)
end end
def is_paginated?(resource) def is_paginated?(collection)
resource.respond_to?(:current_page) && collection.respond_to?(:current_page) &&
resource.respond_to?(:total_pages) && collection.respond_to?(:total_pages) &&
resource.respond_to?(:size) collection.respond_to?(:size)
end end
end end
end end

View File

@ -4,7 +4,6 @@ module ActiveModel
class Adapter class Adapter
class JsonApi < Adapter class JsonApi < Adapter
class FragmentCache class FragmentCache
def fragment_cache(root, cached_hash, non_cached_hash) def fragment_cache(root, cached_hash, non_cached_hash)
hash = {} hash = {}
core_cached = cached_hash.first core_cached = cached_hash.first
@ -16,7 +15,6 @@ module ActiveModel
hash.deep_merge no_root_non_cache.deep_merge no_root_cache hash.deep_merge no_root_non_cache.deep_merge no_root_cache
end end
end end
end end
end end

View File

@ -3,23 +3,22 @@ module ActiveModel
class ArraySerializer class ArraySerializer
NoSerializerError = Class.new(StandardError) NoSerializerError = Class.new(StandardError)
include Enumerable include Enumerable
delegate :each, to: :@objects delegate :each, to: :@serializers
attr_reader :root, :meta, :meta_key attr_reader :object, :root, :meta, :meta_key
def initialize(objects, options = {}) def initialize(resources, options = {})
@root = options[:root] @root = options[:root]
@resource = objects @object = resources
@objects = objects.map do |object| @serializers = resources.map do |resource|
serializer_class = options.fetch( serializer_class = options.fetch(:serializer) {
:serializer, ActiveModel::Serializer.serializer_for(resource)
ActiveModel::Serializer.serializer_for(object) }
)
if serializer_class.nil? if serializer_class.nil?
fail NoSerializerError, "No serializer found for object: #{object.inspect}" fail NoSerializerError, "No serializer found for resource: #{resource.inspect}"
else else
serializer_class.new(object, options.except(:serializer)) serializer_class.new(resource, options.except(:serializer))
end end
end end
@meta = options[:meta] @meta = options[:meta]
@ -27,7 +26,7 @@ module ActiveModel
end end
def json_key def json_key
key = root || @objects.first.try(:json_key) || @resource.try(:name).try(:underscore) key = root || @serializers.first.try(:json_key) || object.try(:name).try(:underscore)
key.try(:pluralize) key.try(:pluralize)
end end
end end

View File

@ -7,10 +7,9 @@ module ActiveModel
# @param [Hash{Symbol => Object}] options # @param [Hash{Symbol => Object}] options
# #
# @example # @example
# Association.new(:comments, CommentSummarySerializer, embed: :ids) # Association.new(:comments, CommentSummarySerializer)
# #
Association = Struct.new(:name, :serializer, :options) do Association = Struct.new(:name, :serializer, :options) do
# @return [Symbol] # @return [Symbol]
# #
def key def key

View File

@ -1,7 +1,6 @@
module ActiveModel module ActiveModel
class Serializer class Serializer
class Fieldset class Fieldset
def initialize(fields, root = nil) def initialize(fields, root = nil)
@root = root @root = root
@raw_fields = fields @raw_fields = fields
@ -36,7 +35,6 @@ module ActiveModel
{} {}
end end
end end
end end
end end
end end

View File

@ -15,7 +15,6 @@ module ActiveModel::Serializer::Lint
# always return +{}+, and the tests would pass. It is up to you to ensure # always return +{}+, and the tests would pass. It is up to you to ensure
# that the values are semantically meaningful. # that the values are semantically meaningful.
module Tests module Tests
# Passes if the object responds to <tt>serializable_hash</tt> and if it takes # Passes if the object responds to <tt>serializable_hash</tt> and if it takes
# zero or one arguments. # zero or one arguments.
# Fails otherwise. # Fails otherwise.
@ -23,7 +22,7 @@ module ActiveModel::Serializer::Lint
# <tt>serializable_hash</tt> returns a hash representation of a object's attributes. # <tt>serializable_hash</tt> returns a hash representation of a object's attributes.
# Typically, it is implemented by including ActiveModel::Serialization. # Typically, it is implemented by including ActiveModel::Serialization.
def test_serializable_hash def test_serializable_hash
assert_respond_to resource, :serializable_hash, "The resource should respond to serializable_hash" assert_respond_to resource, :serializable_hash, 'The resource should respond to serializable_hash'
resource.serializable_hash resource.serializable_hash
resource.serializable_hash(nil) resource.serializable_hash(nil)
end end
@ -35,8 +34,18 @@ module ActiveModel::Serializer::Lint
# <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'
assert_equal resource.method(:read_attribute_for_serialization).arity, 1 actual_arity = resource.method(:read_attribute_for_serialization).arity
if defined?(::Rubinius)
# 1 for def read_attribute_for_serialization(name); end
# -2 for alias :read_attribute_for_serialization :send for rbx because :shrug:
assert_includes [1, -2], actual_arity, "expected #{actual_arity.inspect} to be 1 or -2"
else
# using absolute value since arity is:
# 1 for def read_attribute_for_serialization(name); end
# -1 for alias :read_attribute_for_serialization :send
assert_includes [1, -1], actual_arity, "expected #{actual_arity.inspect} to be 1 or -1"
end
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
@ -68,7 +77,7 @@ module ActiveModel::Serializer::Lint
end end
# Passes if the object responds to <tt>cache_key</tt> and if it takes no # Passes if the object responds to <tt>cache_key</tt> and if it takes no
# arguments. # arguments (Rails 4.0) or a splat (Rails 4.1+).
# 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,
@ -76,7 +85,11 @@ module ActiveModel::Serializer::Lint
# It is not required unless caching is enabled. # 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
assert_equal resource.method(:cache_key).arity, 0 actual_arity = resource.method(:cache_key).arity
# using absolute value since arity is:
# 0 for Rails 4.1+, *timestamp_names
# -1 for Rails 4.0, no arguments
assert_includes [-1, 0], actual_arity, "expected #{actual_arity.inspect} to be 0 or -1"
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
@ -112,6 +125,5 @@ module ActiveModel::Serializer::Lint
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

View File

@ -1,5 +1,5 @@
module ActiveModel module ActiveModel
class Serializer class Serializer
VERSION = "0.10.0.rc2" VERSION = '0.10.0.rc2'
end end
end end

View File

@ -8,24 +8,21 @@ module ActiveModelSerializers
ensure ensure
$VERBOSE = verbose $VERBOSE = verbose
end end
end end
require 'active_model' require 'active_model'
require 'active_model/serializer/version' require 'action_controller'
require 'active_model/serializer' require 'active_model/serializer'
require 'active_model/serializable_resource' require 'active_model/serializable_resource'
require 'active_model/serializer/version'
begin
require 'active_model/serializer/railtie'
require 'action_controller'
require 'action_controller/serialization' require 'action_controller/serialization'
ActiveSupport.on_load(:action_controller) do ActiveSupport.on_load(:action_controller) do
include ::ActionController::Serialization include ::ActionController::Serialization
ActionDispatch::Reloader.to_prepare do ActionDispatch::Reloader.to_prepare do
ActiveModel::Serializer.serializers_cache.clear ActiveModel::Serializer.serializers_cache.clear
end end
end end
rescue LoadError
# rails not installed, continuing require 'active_model/serializer/railtie'
end

View File

@ -1,15 +1,15 @@
module Rails 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', File.join('app/serializers', class_path, "#{file_name}_serializer.rb") template 'serializer.rb.erb', File.join('app/serializers', class_path, "#{file_name}_serializer.rb")
end end
private private
@ -26,9 +26,9 @@ module Rails
if options[:parent] if options[:parent]
options[:parent] options[:parent]
elsif defined?(::ApplicationSerializer) elsif defined?(::ApplicationSerializer)
"ApplicationSerializer" 'ApplicationSerializer'
else else
"ActiveModel::Serializer" 'ActiveModel::Serializer'
end end
end end
end end

0
lib/tasks/rubocop.rake Normal file
View File

View File

@ -33,10 +33,10 @@ module ActionController
expected = { expected = {
data: { data: {
id: assigns(:profile).id.to_s, id: assigns(:profile).id.to_s,
type: "profiles", type: 'profiles',
attributes: { attributes: {
name: "Name 1", name: 'Name 1',
description: "Description 1", description: 'Description 1',
} }
} }
} }

View File

@ -100,11 +100,11 @@ module ActionController
get :render_array_using_explicit_serializer_and_custom_serializers get :render_array_using_explicit_serializer_and_custom_serializers
expected = [ expected = [
{ "title" => "New Post", { 'title' => 'New Post',
"body" => "Body", 'body' => 'Body',
"id" => assigns(:post).id, 'id' => assigns(:post).id,
"comments" => [{"id" => 1}, {"id" => 2}], 'comments' => [{ 'id' => 1 }, { 'id' => 2 }],
"author" => { "id" => assigns(:author).id } 'author' => { 'id' => assigns(:author).id }
} }
] ]
@ -116,13 +116,13 @@ module ActionController
expected = { expected = {
id: 1337, id: 1337,
name: "Amazing Place", name: 'Amazing Place',
locations: [ locations: [
{ {
id: 42, id: 42,
lat: "-23.550520", lat: '-23.550520',
lng: "-46.633309", lng: '-46.633309',
place: "Nowhere" # is a virtual attribute on LocationSerializer place: 'Nowhere' # is a virtual attribute on LocationSerializer
} }
] ]
} }

View File

@ -28,10 +28,10 @@ module ActionController
@first_comment.author = @author2 @first_comment.author = @author2
@second_comment.post = @post @second_comment.post = @post
@second_comment.author = nil @second_comment.author = nil
@post2 = Post.new(id: 2, title: "Another Post", body: "Body") @post2 = Post.new(id: 2, title: 'Another Post', body: 'Body')
@post2.author = @author @post2.author = @author
@post2.comments = [] @post2.comments = []
@blog = Blog.new(id: 1, name: "My Blog!!") @blog = Blog.new(id: 1, name: 'My Blog!!')
@post.blog = @blog @post.blog = @blog
@post2.blog = @blog @post2.blog = @blog
end end
@ -75,7 +75,7 @@ module ActionController
def render_collection_with_include def render_collection_with_include
setup_post setup_post
render json: [@post], include: ['author', 'comments'], adapter: :json_api render json: [@post], include: %w(author comments), adapter: :json_api
end end
end end
@ -100,37 +100,37 @@ module ActionController
response = JSON.parse(@response.body) response = JSON.parse(@response.body)
expected_linked = [ expected_linked = [
{ {
"id" => "1", 'id' => '1',
"type" => "authors", 'type' => 'authors',
"attributes" => { 'attributes' => {
"name" => "Steve K." 'name' => 'Steve K.'
}, },
"relationships" => { 'relationships' => {
"posts" => { "data" => [] }, 'posts' => { 'data' => [] },
"roles" => { "data" => [{ "type" =>"roles", "id" => "1" }, { "type" =>"roles", "id" => "2" }] }, 'roles' => { 'data' => [{ 'type' => 'roles', 'id' => '1' }, { 'type' => 'roles', 'id' => '2' }] },
"bio" => { "data" => nil } 'bio' => { 'data' => nil }
} }
}, { }, {
"id" => "1", 'id' => '1',
"type" => "roles", 'type' => 'roles',
"attributes" => { 'attributes' => {
"name" => "admin", 'name' => 'admin',
"description" => nil, 'description' => nil,
"slug" => "admin-1" 'slug' => 'admin-1'
}, },
"relationships" => { 'relationships' => {
"author" => { "data" => { "type" =>"authors", "id" => "1" } } 'author' => { 'data' => { 'type' => 'authors', 'id' => '1' } }
} }
}, { }, {
"id" => "2", 'id' => '2',
"type" => "roles", 'type' => 'roles',
"attributes" => { 'attributes' => {
"name" => "colab", 'name' => 'colab',
"description" => nil, 'description' => nil,
"slug" => "colab-2" 'slug' => 'colab-2'
}, },
"relationships" => { 'relationships' => {
"author" => { "data" => { "type" =>"authors", "id" => "1" } } 'author' => { 'data' => { 'type' => 'authors', 'id' => '1' } }
} }
} }
] ]

View File

@ -47,11 +47,11 @@ module ActionController
tests PaginationTestController tests PaginationTestController
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, page: { number: 2, size: 1 } get :render_pagination_using_will_paginate, page: { number: 2, size: 1 }
response = JSON.parse(@response.body) response = JSON.parse(@response.body)
@ -59,48 +59,48 @@ module ActionController
end end
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, page: { number: 1, size: 2 } get :render_pagination_using_will_paginate, 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']
end end
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, page: { number: 2, size: 1 } get :render_pagination_using_kaminari, 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']
end end
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, page: { number: 3, size: 1 } get :render_pagination_using_kaminari, 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']
end end
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, page: { number: 1, size: 2 }, teste: "additional" get :render_pagination_using_will_paginate, 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']
end end
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, page: { number: 3, size: 1 }, teste: "additional" get :render_pagination_using_kaminari, 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']
end end

View File

@ -1,4 +1,3 @@
require 'test_helper' require 'test_helper'
module ActionController module ActionController
@ -22,20 +21,20 @@ module ActionController
def render_array_using_custom_root def render_array_using_custom_root
with_adapter ActiveModel::Serializer::Adapter::Json do with_adapter ActiveModel::Serializer::Adapter::Json do
@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], root: "custom_root" render json: [@profile], root: 'custom_root'
end end
end end
def render_array_that_is_empty_using_custom_root def render_array_that_is_empty_using_custom_root
with_adapter ActiveModel::Serializer::Adapter::Json do with_adapter ActiveModel::Serializer::Adapter::Json do
render json: [], root: "custom_root" render json: [], root: 'custom_root'
end end
end end
def render_object_using_custom_root def render_object_using_custom_root
with_adapter ActiveModel::Serializer::Adapter::Json do with_adapter ActiveModel::Serializer::Adapter::Json do
@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, root: "custom_root" render json: @profile, root: 'custom_root'
end end
end end
@ -49,7 +48,6 @@ module ActionController
def render_array_using_implicit_serializer_and_meta def render_array_using_implicit_serializer_and_meta
with_adapter ActiveModel::Serializer::Adapter::JsonApi do with_adapter ActiveModel::Serializer::Adapter::JsonApi do
@profiles = [ @profiles = [
Profile.new({ name: 'Name 1', description: 'Description 1', comments: 'Comments 1' }) Profile.new({ name: 'Name 1', description: 'Description 1', comments: 'Comments 1' })
] ]
@ -139,6 +137,7 @@ module ActionController
end end
private private
def generate_cached_serializer(obj) def generate_cached_serializer(obj)
ActiveModel::SerializableResource.new(obj).to_json ActiveModel::SerializableResource.new(obj).to_json
end end
@ -160,8 +159,8 @@ module ActionController
get :render_using_implicit_serializer get :render_using_implicit_serializer
expected = { expected = {
name: "Name 1", name: 'Name 1',
description: "Description 1" description: 'Description 1'
} }
assert_equal 'application/json', @response.content_type assert_equal 'application/json', @response.content_type
@ -174,10 +173,10 @@ module ActionController
expected = { expected = {
data: { data: {
id: assigns(:profile).id.to_s, id: assigns(:profile).id.to_s,
type: "profiles", type: 'profiles',
attributes: { attributes: {
name: "Name 1", name: 'Name 1',
description: "Description 1" description: 'Description 1'
} }
} }
} }
@ -189,7 +188,7 @@ module ActionController
def test_render_array_using_custom_root def test_render_array_using_custom_root
get :render_array_using_custom_root get :render_array_using_custom_root
expected = {custom_roots: [{name: "Name 1", description: "Description 1"}]} expected = { custom_roots: [{ name: 'Name 1', description: 'Description 1' }] }
assert_equal 'application/json', @response.content_type assert_equal 'application/json', @response.content_type
assert_equal expected.to_json, @response.body assert_equal expected.to_json, @response.body
end end
@ -205,7 +204,7 @@ module ActionController
def test_render_object_using_custom_root def test_render_object_using_custom_root
get :render_object_using_custom_root get :render_object_using_custom_root
expected = {custom_root: {name: "Name 1", description: "Description 1"}} expected = { custom_root: { name: 'Name 1', description: 'Description 1' } }
assert_equal 'application/json', @response.content_type assert_equal 'application/json', @response.content_type
assert_equal expected.to_json, @response.body assert_equal expected.to_json, @response.body
end end
@ -251,10 +250,10 @@ module ActionController
data: [ data: [
{ {
id: assigns(:profiles).first.id.to_s, id: assigns(:profiles).first.id.to_s,
type: "profiles", type: 'profiles',
attributes: { attributes: {
name: "Name 1", name: 'Name 1',
description: "Description 1" description: 'Description 1'
} }
} }
], ],
@ -336,8 +335,8 @@ module ActionController
response = JSON.parse(@response.body) response = JSON.parse(@response.body)
assert_equal 'application/json', @response.content_type assert_equal 'application/json', @response.content_type
assert_equal 'ZOMG A ROLE', response["name"] assert_equal 'ZOMG A ROLE', response['name']
assert_equal 'HUEHUEBRBR', response["description"] assert_equal 'HUEHUEBRBR', response['description']
end end
def test_render_with_fragment_except_cache_enable def test_render_with_fragment_except_cache_enable
@ -346,8 +345,8 @@ module ActionController
response = JSON.parse(@response.body) response = JSON.parse(@response.body)
assert_equal 'application/json', @response.content_type assert_equal 'application/json', @response.content_type
assert_equal 5, response["rating"] assert_equal 5, response['rating']
assert_equal 'lol', response["content"] assert_equal 'lol', response['content']
end end
def test_render_fragment_changed_object_with_relationship def test_render_fragment_changed_object_with_relationship
@ -358,11 +357,11 @@ module ActionController
response = JSON.parse(@response.body) response = JSON.parse(@response.body)
expected_return = { expected_return = {
"id"=>1, 'id' => 1,
"time"=>Time.now.to_s, 'time' => Time.now.to_s,
"likeable" => { 'likeable' => {
"id"=>1, 'id' => 1,
"body"=>"ZOMG A COMMENT" 'body' => 'ZOMG A COMMENT'
} }
} }
@ -386,7 +385,7 @@ module ActionController
], ],
blog: { blog: {
id: 999, id: 999,
name: "Custom blog" name: 'Custom blog'
}, },
author: { author: {
id: 1, id: 1,
@ -417,7 +416,7 @@ module ActionController
true true
end end
}.new }.new
assert_equal "", (capture(:stderr) { assert_equal '', (capture(:stderr) {
controller.get_serializer(Profile.new) controller.get_serializer(Profile.new)
}) })
end end

View File

@ -4,7 +4,7 @@ module ActiveModel
class Adapter class Adapter
class FragmentCacheTest < Minitest::Test class FragmentCacheTest < Minitest::Test
def setup def setup
@spam = Spam::UnrelatedLink.new(id: "spam-id-1") @spam = Spam::UnrelatedLink.new(id: 'spam-id-1')
@author = Author.new(name: 'Joao M. D. Moura') @author = Author.new(name: 'Joao M. D. Moura')
@role = Role.new(name: 'Great Author', description: nil) @role = Role.new(name: 'Great Author', description: nil)
@role.author = [@author] @role.author = [@author]

View File

@ -14,7 +14,7 @@ module ActiveModel
@comment.post = @post @comment.post = @post
@comment.author = nil @comment.author = nil
@anonymous_post.author = nil @anonymous_post.author = nil
@blog = Blog.new(id: 1, name: "My Blog!!") @blog = Blog.new(id: 1, name: 'My Blog!!')
@post.blog = @blog @post.blog = @blog
@anonymous_post.blog = nil @anonymous_post.blog = nil
@ -31,14 +31,14 @@ module ActiveModel
serializer = PostSerializer.new(@anonymous_post) serializer = PostSerializer.new(@anonymous_post)
adapter = ActiveModel::Serializer::Adapter::Json.new(serializer) adapter = ActiveModel::Serializer::Adapter::Json.new(serializer)
assert_equal({post: {title: "Hello!!", body: "Hello, world!!", id: 43, comments: [], blog: {id: 999, name: "Custom blog"}, author: nil}}, adapter.serializable_hash) assert_equal({ post: { title: 'Hello!!', body: 'Hello, world!!', id: 43, comments: [], blog: { id: 999, name: 'Custom blog' }, author: nil } }, adapter.serializable_hash)
end end
def test_include_nil_author_with_specified_serializer def test_include_nil_author_with_specified_serializer
serializer = PostPreviewSerializer.new(@anonymous_post) serializer = PostPreviewSerializer.new(@anonymous_post)
adapter = ActiveModel::Serializer::Adapter::Json.new(serializer) adapter = ActiveModel::Serializer::Adapter::Json.new(serializer)
assert_equal({post: {title: "Hello!!", body: "Hello, world!!", id: 43, comments: [], author: nil}}, adapter.serializable_hash) assert_equal({ post: { title: 'Hello!!', body: 'Hello, world!!', id: 43, comments: [], author: nil } }, adapter.serializable_hash)
end end
end end
end end

View File

@ -13,7 +13,7 @@ module ActiveModel
@second_post.comments = [] @second_post.comments = []
@first_post.author = @author @first_post.author = @author
@second_post.author = @author @second_post.author = @author
@blog = Blog.new(id: 1, name: "My Blog!!") @blog = Blog.new(id: 1, name: 'My Blog!!')
@first_post.blog = @blog @first_post.blog = @blog
@second_post.blog = nil @second_post.blog = nil
@ -21,15 +21,15 @@ module ActiveModel
end end
def test_with_serializer_option def test_with_serializer_option
@blog.special_attribute = "Special" @blog.special_attribute = 'Special'
@blog.articles = [@first_post, @second_post] @blog.articles = [@first_post, @second_post]
serializer = ArraySerializer.new([@blog], serializer: CustomBlogSerializer) serializer = ArraySerializer.new([@blog], serializer: CustomBlogSerializer)
adapter = ActiveModel::Serializer::Adapter::Json.new(serializer) adapter = ActiveModel::Serializer::Adapter::Json.new(serializer)
expected = { blogs: [{ expected = { blogs: [{
id: 1, id: 1,
special_attribute: "Special", special_attribute: 'Special',
articles: [{id: 1,title: "Hello!!", body: "Hello, world!!"}, {id: 2, title: "New Post", body: "Body"}] articles: [{ id: 1, title: 'Hello!!', body: 'Hello, world!!' }, { id: 2, title: 'New Post', body: 'Body' }]
}] } }] }
assert_equal expected, adapter.serializable_hash assert_equal expected, adapter.serializable_hash
end end
@ -39,30 +39,30 @@ module ActiveModel
adapter = ActiveModel::Serializer::Adapter::Json.new(serializer) adapter = ActiveModel::Serializer::Adapter::Json.new(serializer)
expected = { posts: [{ expected = { posts: [{
title: "Hello!!", title: 'Hello!!',
body: "Hello, world!!", body: 'Hello, world!!',
id: 1, id: 1,
comments: [], comments: [],
author: { author: {
id: 1, id: 1,
name: "Steve K." name: 'Steve K.'
}, },
blog: { blog: {
id: 999, id: 999,
name: "Custom blog" name: 'Custom blog'
} }
}, { }, {
title: "New Post", title: 'New Post',
body: "Body", body: 'Body',
id: 2, id: 2,
comments: [], comments: [],
author: { author: {
id: 1, id: 1,
name: "Steve K." name: 'Steve K.'
}, },
blog: { blog: {
id: 999, id: 999,
name: "Custom blog" name: 'Custom blog'
} }
}] } }] }
assert_equal expected, adapter.serializable_hash assert_equal expected, adapter.serializable_hash

View File

@ -15,9 +15,9 @@ module ActiveModel
@post.author = @author @post.author = @author
@first_comment.post = @post @first_comment.post = @post
@second_comment.post = @post @second_comment.post = @post
@blog = Blog.new(id: 1, name: "My Blog!!") @blog = Blog.new(id: 1, name: 'My Blog!!')
@post.blog = @blog @post.blog = @blog
@tag = Tag.new(id: 1, name: "#hash_tag") @tag = Tag.new(id: 1, name: '#hash_tag')
@post.tags = [@tag] @post.tags = [@tag]
end end
@ -36,7 +36,7 @@ module ActiveModel
assert_equal({ assert_equal({
id: 42, id: 42,
tags: [ tags: [
{"attributes"=>{"id"=>1, "name"=>"#hash_tag"}} { 'attributes' => { 'id' => 1, 'name' => '#hash_tag' } }
] ]
}.to_json, adapter.serializable_hash[:post].to_json) }.to_json, adapter.serializable_hash[:post].to_json)
end end

View File

@ -21,7 +21,7 @@ module ActiveModel
@comment.author = nil @comment.author = nil
@post.author = @author @post.author = @author
@anonymous_post.author = nil @anonymous_post.author = nil
@blog = Blog.new(id: 1, name: "My Blog!!") @blog = Blog.new(id: 1, name: 'My Blog!!')
@blog.writer = @author @blog.writer = @author
@blog.articles = [@post, @anonymous_post] @blog.articles = [@post, @anonymous_post]
@author.posts = [] @author.posts = []
@ -32,7 +32,7 @@ module ActiveModel
end end
def test_includes_post_id def test_includes_post_id
expected = { data: { type: "posts", id: "42" } } expected = { data: { type: 'posts', id: '42' } }
assert_equal(expected, @adapter.serializable_hash[:data][:relationships][:post]) assert_equal(expected, @adapter.serializable_hash[:data][:relationships][:post])
end end
@ -40,16 +40,16 @@ module ActiveModel
def test_includes_linked_post def test_includes_linked_post
@adapter = ActiveModel::Serializer::Adapter::JsonApi.new(@serializer, include: 'post') @adapter = ActiveModel::Serializer::Adapter::JsonApi.new(@serializer, include: 'post')
expected = [{ expected = [{
id: "42", id: '42',
type: "posts", type: 'posts',
attributes: { attributes: {
title: 'New Post', title: 'New Post',
body: 'Body', body: 'Body',
}, },
relationships: { relationships: {
comments: { data: [ { type: "comments", id: "1" } ] }, comments: { data: [{ type: 'comments', id: '1' }] },
blog: { data: { type: "blogs", id: "999" } }, blog: { data: { type: 'blogs', id: '999' } },
author: { data: { type: "authors", id: "1" } } author: { data: { type: 'authors', id: '1' } }
} }
}] }]
assert_equal expected, @adapter.serializable_hash[:included] assert_equal expected, @adapter.serializable_hash[:included]
@ -58,15 +58,15 @@ module ActiveModel
def test_limiting_linked_post_fields def test_limiting_linked_post_fields
@adapter = ActiveModel::Serializer::Adapter::JsonApi.new(@serializer, include: 'post', fields: { post: [:title] }) @adapter = ActiveModel::Serializer::Adapter::JsonApi.new(@serializer, include: 'post', fields: { post: [:title] })
expected = [{ expected = [{
id: "42", id: '42',
type: "posts", type: 'posts',
attributes: { attributes: {
title: 'New Post' title: 'New Post'
}, },
relationships: { relationships: {
comments: { data: [ { type: "comments", id: "1" } ] }, comments: { data: [{ type: 'comments', id: '1' }] },
blog: { data: { type: "blogs", id: "999" } }, blog: { data: { type: 'blogs', id: '999' } },
author: { data: { type: "authors", id: "1" } } author: { data: { type: 'authors', id: '1' } }
} }
}] }]
assert_equal expected, @adapter.serializable_hash[:included] assert_equal expected, @adapter.serializable_hash[:included]
@ -76,7 +76,7 @@ module ActiveModel
serializer = PostSerializer.new(@anonymous_post) serializer = PostSerializer.new(@anonymous_post)
adapter = ActiveModel::Serializer::Adapter::JsonApi.new(serializer) adapter = ActiveModel::Serializer::Adapter::JsonApi.new(serializer)
assert_equal({comments: { data: [] }, blog: { data: { type: "blogs", id: "999" } }, author: { data: nil }}, adapter.serializable_hash[:data][:relationships]) assert_equal({ comments: { data: [] }, blog: { data: { type: 'blogs', id: '999' } }, author: { data: nil } }, adapter.serializable_hash[:data][:relationships])
end end
def test_include_type_for_association_when_different_than_name def test_include_type_for_association_when_different_than_name
@ -86,19 +86,19 @@ module ActiveModel
expected = { expected = {
writer: { writer: {
data: { data: {
type: "authors", type: 'authors',
id: "1" id: '1'
} }
}, },
articles: { articles: {
data: [ data: [
{ {
type: "posts", type: 'posts',
id: "42" id: '42'
}, },
{ {
type: "posts", type: 'posts',
id: "43" id: '43'
} }
] ]
} }
@ -108,14 +108,14 @@ module ActiveModel
def test_include_linked_resources_with_type_name def test_include_linked_resources_with_type_name
serializer = BlogSerializer.new(@blog) serializer = BlogSerializer.new(@blog)
adapter = ActiveModel::Serializer::Adapter::JsonApi.new(serializer, include: ['writer', 'articles']) adapter = ActiveModel::Serializer::Adapter::JsonApi.new(serializer, include: %w(writer articles))
linked = adapter.serializable_hash[:included] linked = adapter.serializable_hash[:included]
expected = [ expected = [
{ {
id: "1", id: '1',
type: "authors", type: 'authors',
attributes: { attributes: {
name: "Steve K." name: 'Steve K.'
}, },
relationships: { relationships: {
posts: { data: [] }, posts: { data: [] },
@ -123,27 +123,27 @@ module ActiveModel
bio: { data: nil } bio: { data: nil }
} }
}, { }, {
id: "42", id: '42',
type: "posts", type: 'posts',
attributes: { attributes: {
title: "New Post", title: 'New Post',
body: "Body" body: 'Body'
}, },
relationships: { relationships: {
comments: { data: [ { type: "comments", id: "1" } ] }, comments: { data: [{ type: 'comments', id: '1' }] },
blog: { data: { type: "blogs", id: "999" } }, blog: { data: { type: 'blogs', id: '999' } },
author: { data: { type: "authors", id: "1" } } author: { data: { type: 'authors', id: '1' } }
} }
}, { }, {
id: "43", id: '43',
type: "posts", type: 'posts',
attributes: { attributes: {
title: "Hello!!", title: 'Hello!!',
body: "Hello, world!!" body: 'Hello, world!!'
}, },
relationships: { relationships: {
comments: { data: [] }, comments: { data: [] },
blog: { data: { type: "blogs", id: "999" } }, blog: { data: { type: 'blogs', id: '999' } },
author: { data: nil } author: { data: nil }
} }
} }

View File

@ -27,29 +27,29 @@ module ActiveModel
def test_include_multiple_posts def test_include_multiple_posts
expected = [ expected = [
{ {
id: "1", id: '1',
type: "posts", type: 'posts',
attributes: { attributes: {
title: "Hello!!", title: 'Hello!!',
body: "Hello, world!!" body: 'Hello, world!!'
}, },
relationships: { relationships: {
comments: { data: [] }, comments: { data: [] },
blog: { data: { type: "blogs", id: "999" } }, blog: { data: { type: 'blogs', id: '999' } },
author: { data: { type: "authors", id: "1" } } author: { data: { type: 'authors', id: '1' } }
} }
}, },
{ {
id: "2", id: '2',
type: "posts", type: 'posts',
attributes: { attributes: {
title: "New Post", title: 'New Post',
body: "Body" body: 'Body'
}, },
relationships: { relationships: {
comments: { data: [] }, comments: { data: [] },
blog: { data: { type: "blogs", id: "999" } }, blog: { data: { type: 'blogs', id: '999' } },
author: { data: { type: "authors", id: "1" } } author: { data: { type: 'authors', id: '1' } }
} }
} }
] ]
@ -62,33 +62,32 @@ module ActiveModel
expected = [ expected = [
{ {
id: "1", id: '1',
type: "posts", type: 'posts',
attributes: { attributes: {
title: "Hello!!" title: 'Hello!!'
}, },
relationships: { relationships: {
comments: { data: [] }, comments: { data: [] },
blog: { data: { type: "blogs", id: "999" } }, blog: { data: { type: 'blogs', id: '999' } },
author: { data: { type: "authors", id: "1" } } author: { data: { type: 'authors', id: '1' } }
} }
}, },
{ {
id: "2", id: '2',
type: "posts", type: 'posts',
attributes: { attributes: {
title: "New Post" title: 'New Post'
}, },
relationships: { relationships: {
comments: { data: [] }, comments: { data: [] },
blog: { data: { type: "blogs", id: "999" } }, blog: { data: { type: 'blogs', id: '999' } },
author: { data: { type: "authors", id: "1" } } author: { data: { type: 'authors', id: '1' } }
} }
} }
] ]
assert_equal(expected, @adapter.serializable_hash[:data]) assert_equal(expected, @adapter.serializable_hash[:data])
end end
end end
end end
end end

View File

@ -27,8 +27,8 @@ module ActiveModel
def test_includes_comment_ids def test_includes_comment_ids
expected = { expected = {
data: [ data: [
{ type: "posts", id: "1"}, { type: 'posts', id: '1' },
{ type: "posts", id: "2"} { type: 'posts', id: '2' }
] ]
} }

View File

@ -24,7 +24,7 @@ module ActiveModel
@serializer = PostPreviewSerializer.new(@post) @serializer = PostPreviewSerializer.new(@post)
@adapter = ActiveModel::Serializer::Adapter::JsonApi.new( @adapter = ActiveModel::Serializer::Adapter::JsonApi.new(
@serializer, @serializer,
include: ['comments', 'author'] include: %w(comments author)
) )
end end
@ -58,9 +58,9 @@ module ActiveModel
}, },
{ {
id: @author.id.to_s, id: @author.id.to_s,
type: "authors", type: 'authors',
relationships: { relationships: {
posts: { data: [ {type: "posts", id: @post.id.to_s } ] } posts: { data: [{ type: 'posts', id: @post.id.to_s }] }
} }
} }
] ]
@ -70,7 +70,7 @@ module ActiveModel
def test_includes_author_id def test_includes_author_id
expected = { expected = {
data: { type: "authors", id: @author.id.to_s } data: { type: 'authors', id: @author.id.to_s }
} }
assert_equal(expected, @adapter.serializable_hash[:data][:relationships][:author]) assert_equal(expected, @adapter.serializable_hash[:data][:relationships][:author])

View File

@ -22,12 +22,12 @@ module ActiveModel
@second_comment.post = @post @second_comment.post = @post
@post.author = @author @post.author = @author
@post_without_comments.author = nil @post_without_comments.author = nil
@blog = Blog.new(id: 1, name: "My Blog!!") @blog = Blog.new(id: 1, name: 'My Blog!!')
@blog.writer = @author @blog.writer = @author
@blog.articles = [@post] @blog.articles = [@post]
@post.blog = @blog @post.blog = @blog
@post_without_comments.blog = nil @post_without_comments.blog = nil
@tag = Tag.new(id: 1, name: "#hash_tag") @tag = Tag.new(id: 1, name: '#hash_tag')
@post.tags = [@tag] @post.tags = [@tag]
@serializer = PostSerializer.new(@post) @serializer = PostSerializer.new(@post)
@adapter = ActiveModel::Serializer::Adapter::JsonApi.new(@serializer) @adapter = ActiveModel::Serializer::Adapter::JsonApi.new(@serializer)
@ -36,7 +36,7 @@ module ActiveModel
end end
def test_includes_comment_ids def test_includes_comment_ids
expected = { data: [ { type: "comments", id: "1" }, { type: "comments", id: "2" } ] } expected = { data: [{ type: 'comments', id: '1' }, { type: 'comments', id: '2' }] }
assert_equal(expected, @adapter.serializable_hash[:data][:relationships][:comments]) assert_equal(expected, @adapter.serializable_hash[:data][:relationships][:comments])
end end
@ -44,23 +44,23 @@ module ActiveModel
def test_includes_linked_comments def test_includes_linked_comments
@adapter = ActiveModel::Serializer::Adapter::JsonApi.new(@serializer, include: 'comments') @adapter = ActiveModel::Serializer::Adapter::JsonApi.new(@serializer, include: 'comments')
expected = [{ expected = [{
id: "1", id: '1',
type: "comments", type: 'comments',
attributes: { attributes: {
body: 'ZOMG A COMMENT' body: 'ZOMG A COMMENT'
}, },
relationships: { relationships: {
post: { data: { type: "posts", id: "1" } }, post: { data: { type: 'posts', id: '1' } },
author: { data: nil } author: { data: nil }
} }
}, { }, {
id: "2", id: '2',
type: "comments", type: 'comments',
attributes: { attributes: {
body: 'ZOMG ANOTHER COMMENT' body: 'ZOMG ANOTHER COMMENT'
}, },
relationships: { relationships: {
post: { data: { type: "posts", id: "1" } }, post: { data: { type: 'posts', id: '1' } },
author: { data: nil } author: { data: nil }
} }
}] }]
@ -70,17 +70,17 @@ module ActiveModel
def test_limit_fields_of_linked_comments def test_limit_fields_of_linked_comments
@adapter = ActiveModel::Serializer::Adapter::JsonApi.new(@serializer, include: 'comments', fields: { comment: [:id] }) @adapter = ActiveModel::Serializer::Adapter::JsonApi.new(@serializer, include: 'comments', fields: { comment: [:id] })
expected = [{ expected = [{
id: "1", id: '1',
type: "comments", type: 'comments',
relationships: { relationships: {
post: { data: { type: "posts", id: "1" } }, post: { data: { type: 'posts', id: '1' } },
author: { data: nil } author: { data: nil }
} }
}, { }, {
id: "2", id: '2',
type: "comments", type: 'comments',
relationships: { relationships: {
post: { data: { type: "posts", id: "1" } }, post: { data: { type: 'posts', id: '1' } },
author: { data: nil } author: { data: nil }
} }
}] }]
@ -101,8 +101,8 @@ module ActiveModel
expected = { expected = {
data: [{ data: [{
type: "posts", type: 'posts',
id: "1" id: '1'
}] }]
} }
assert_equal expected, actual assert_equal expected, actual
@ -114,8 +114,8 @@ module ActiveModel
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] }
} }
@ -129,8 +129,8 @@ module ActiveModel
assert_equal({ assert_equal({
data: { data: {
id: "1", id: '1',
type: "virtual_values", type: 'virtual_values',
relationships: { relationships: {
maker: { data: { id: 1 } }, maker: { data: { id: 1 } },
reviews: { data: [{ id: 1 }, { id: 2 }] } reviews: { data: [{ id: 1 }, { id: 2 }] }

View File

@ -19,7 +19,7 @@ module ActiveModel
@comment.author = nil @comment.author = nil
@post.author = @author @post.author = @author
@anonymous_post.author = nil @anonymous_post.author = nil
@blog = Blog.new(id: 1, name: "My Blog!!") @blog = Blog.new(id: 1, name: 'My Blog!!')
@blog.writer = @author @blog.writer = @author
@blog.articles = [@post, @anonymous_post] @blog.articles = [@post, @anonymous_post]
@author.posts = [] @author.posts = []
@ -32,7 +32,7 @@ module ActiveModel
end end
def test_includes_bio_id def test_includes_bio_id
expected = { data: { type: "bios", id: "43" } } expected = { data: { type: 'bios', id: '43' } }
assert_equal(expected, @adapter.serializable_hash[:data][:relationships][:bio]) assert_equal(expected, @adapter.serializable_hash[:data][:relationships][:bio])
end end
@ -42,14 +42,14 @@ module ActiveModel
expected = [ expected = [
{ {
id: "43", id: '43',
type: "bios", type: 'bios',
attributes: { attributes: {
content:"AMS Contributor", content: 'AMS Contributor',
rating: nil rating: nil
}, },
relationships: { relationships: {
author: { data: { type: "authors", id: "1" } } author: { data: { type: 'authors', id: '1' } }
} }
} }
] ]
@ -63,8 +63,8 @@ module ActiveModel
expected = { expected = {
data: { data: {
id: "1", id: '1',
type: "virtual_values", type: 'virtual_values',
relationships: { relationships: {
maker: { data: { id: 1 } }, maker: { data: { id: 1 } },
reviews: { data: [{ id: 1 }, { id: 2 }] } reviews: { data: [{ id: 1 }, { id: 2 }] }

View File

@ -14,9 +14,8 @@ module ActiveModel
@first_comment.post = @post @first_comment.post = @post
@second_comment.post = @post @second_comment.post = @post
@post.author = @author @post.author = @author
@blog = Blog.new(id: 1, name: "My Blog!!") @blog = Blog.new(id: 1, name: 'My Blog!!')
@post.blog = @blog @post.blog = @blog
end end
def test_custom_keys def test_custom_keys
@ -25,11 +24,11 @@ module ActiveModel
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"} }, writer: { data: { type: 'authors', id: '1' } },
site: { data: {type: "blogs", id: "1" } } site: { data: { type: 'blogs', id: '1' } }
}, adapter.serializable_hash[:data][:relationships]) }, adapter.serializable_hash[:data][:relationships])
end end
end end

View File

@ -53,94 +53,94 @@ module ActiveModel
expected = { expected = {
data: [ data: [
{ {
id: "10", id: '10',
type: "posts", type: 'posts',
attributes: { attributes: {
title: "Hello!!", title: 'Hello!!',
body: "Hello, world!!" body: 'Hello, world!!'
}, },
relationships: { relationships: {
comments: { data: [ { type: "comments", id: '1' }, { type: "comments", id: '2' } ] }, comments: { data: [{ type: 'comments', id: '1' }, { type: 'comments', id: '2' }] },
blog: { data: { type: "blogs", id: "999" } }, blog: { data: { type: 'blogs', id: '999' } },
author: { data: { type: "authors", id: "1" } } author: { data: { type: 'authors', id: '1' } }
} }
}, },
{ {
id: "20", id: '20',
type: "posts", type: 'posts',
attributes: { attributes: {
title: "New Post", title: 'New Post',
body: "Body" body: 'Body'
}, },
relationships: { relationships: {
comments: { data: [] }, comments: { data: [] },
blog: { data: { type: "blogs", id: "999" } }, blog: { data: { type: 'blogs', id: '999' } },
author: { data: { type: "authors", id: "2" } } author: { data: { type: 'authors', id: '2' } }
} }
} }
], ],
included: [ included: [
{ {
id: "1", id: '1',
type: "comments", type: 'comments',
attributes: { attributes: {
body: "ZOMG A COMMENT" body: 'ZOMG A COMMENT'
}, },
relationships: { relationships: {
post: { data: { type: "posts", id: "10" } }, post: { data: { type: 'posts', id: '10' } },
author: { data: nil } author: { data: nil }
} }
}, { }, {
id: "2", id: '2',
type: "comments", type: 'comments',
attributes: { attributes: {
body: "ZOMG ANOTHER COMMENT", body: 'ZOMG ANOTHER COMMENT',
}, },
relationships: { relationships: {
post: { data: { type: "posts", id: "10" } }, post: { data: { type: 'posts', id: '10' } },
author: { data: nil } author: { data: nil }
} }
}, { }, {
id: "1", id: '1',
type: "authors", type: 'authors',
attributes: { attributes: {
name: "Steve K." name: 'Steve K.'
}, },
relationships: { relationships: {
posts: { data: [ { type: "posts", id: "10" }, { type: "posts", id: "30" } ] }, posts: { data: [{ type: 'posts', id: '10' }, { type: 'posts', id: '30' }] },
roles: { data: [] }, roles: { data: [] },
bio: { data: { type: "bios", id: "1" } } bio: { data: { type: 'bios', id: '1' } }
} }
}, { }, {
id: "1", id: '1',
type: "bios", type: 'bios',
attributes: { attributes: {
content: "AMS Contributor", content: 'AMS Contributor',
rating: nil rating: nil
}, },
relationships: { relationships: {
author: { data: { type: "authors", id: "1" } } author: { data: { type: 'authors', id: '1' } }
} }
}, { }, {
id: "2", id: '2',
type: "authors", type: 'authors',
attributes: { attributes: {
name: "Tenderlove" name: 'Tenderlove'
}, },
relationships: { relationships: {
posts: { data: [ { type: "posts", id:"20" } ] }, posts: { data: [{ type: 'posts', id: '20' }] },
roles: { data: [] }, roles: { data: [] },
bio: { data: { type: "bios", id: "2" } } bio: { data: { type: 'bios', id: '2' } }
} }
}, { }, {
id: "2", id: '2',
type: "bios", type: 'bios',
attributes: { attributes: {
rating: nil, rating: nil,
content: "Rails Contributor", content: 'Rails Contributor',
}, },
relationships: { relationships: {
author: { data: { type: "authors", id: "2" } } author: { data: { type: 'authors', id: '2' } }
} }
} }
] ]
@ -162,39 +162,39 @@ module ActiveModel
expected = [ expected = [
{ {
id: "1", id: '1',
type: "authors", type: 'authors',
attributes: { attributes: {
name: "Steve K." name: 'Steve K.'
}, },
relationships: { relationships: {
posts: { data: [ { type: "posts", id: "10"}, { type: "posts", id: "30" }] }, posts: { data: [{ type: 'posts', id: '10' }, { type: 'posts', id: '30' }] },
roles: { data: [] }, roles: { data: [] },
bio: { data: { type: "bios", id: "1" }} bio: { data: { type: 'bios', id: '1' } }
} }
}, { }, {
id: "10", id: '10',
type: "posts", type: 'posts',
attributes: { attributes: {
title: "Hello!!", title: 'Hello!!',
body: "Hello, world!!" body: 'Hello, world!!'
}, },
relationships: { relationships: {
comments: { data: [ { type: "comments", id: "1"}, { type: "comments", id: "2" }] }, comments: { data: [{ type: 'comments', id: '1' }, { type: 'comments', id: '2' }] },
blog: { data: { type: "blogs", id: "999" } }, blog: { data: { type: 'blogs', id: '999' } },
author: { data: { type: "authors", id: "1" } } author: { data: { type: 'authors', id: '1' } }
} }
}, { }, {
id: "30", id: '30',
type: "posts", type: 'posts',
attributes: { attributes: {
title: "Yet Another Post", title: 'Yet Another Post',
body: "Body" body: 'Body'
}, },
relationships: { relationships: {
comments: { data: [] }, comments: { data: [] },
blog: { data: { type: "blogs", id: "999" } }, blog: { data: { type: 'blogs', id: '999' } },
author: { data: { type: "authors", id: "1" } } author: { data: { type: 'authors', id: '1' } }
} }
} }
] ]
@ -229,21 +229,21 @@ module ActiveModel
expected = [ expected = [
{ {
id: "10", id: '10',
type: "posts", type: 'posts',
attributes: { attributes: {
title: "Hello!!", title: 'Hello!!',
body: "Hello, world!!" body: 'Hello, world!!'
}, },
relationships: { relationships: {
comments: { comments: {
data: [{type: "comments", id: "1"}, {type: "comments", id: "2"}] data: [{ type: 'comments', id: '1' }, { type: 'comments', id: '2' }]
}, },
blog: { blog: {
data: {type: "blogs", id: "999"} data: { type: 'blogs', id: '999' }
}, },
author: { author: {
data: {type: "authors", id: "1"} data: { type: 'authors', id: '1' }
} }
} }
} }
@ -262,14 +262,14 @@ module ActiveModel
expected = { expected = {
data: { data: {
id: "10", id: '10',
type: "posts", type: 'posts',
attributes: { attributes: {
title: "Hello!!", title: 'Hello!!',
body: "Hello, world!!" body: 'Hello, world!!'
}, },
relationships: { relationships: {
comments: { data: [ { type: "comments", id: '1' }, { type: "comments", id: '2' } ] }, comments: { data: [{ type: 'comments', id: '1' }, { type: 'comments', id: '2' }] },
author: { data: nil } author: { data: nil }
} }
} }

View File

@ -43,9 +43,9 @@ module ActiveModel
def data def data
{ data: [ { data: [
{ id:"1", type:"profiles", attributes:{name:"Name 1", description:"Description 1" } }, { id: '1', type: 'profiles', attributes: { name: 'Name 1', description: 'Description 1' } },
{ id:"2", type:"profiles", attributes:{name:"Name 2", description:"Description 2" } }, { id: '2', type: 'profiles', attributes: { name: 'Name 2', description: 'Description 2' } },
{ id:"3", type:"profiles", attributes:{name:"Name 3", description:"Description 3" } } { id: '3', type: 'profiles', attributes: { name: 'Name 3', description: 'Description 3' } }
] ]
} }
end end

View File

@ -21,7 +21,7 @@ module ActiveModel
@comment.author = nil @comment.author = nil
@post.author = @author @post.author = @author
@anonymous_post.author = nil @anonymous_post.author = nil
@blog = Blog.new(id: 1, name: "My Blog!!") @blog = Blog.new(id: 1, name: 'My Blog!!')
@blog.writer = @author @blog.writer = @author
@blog.articles = [@post, @anonymous_post] @blog.articles = [@post, @anonymous_post]
@author.posts = [] @author.posts = []

View File

@ -14,7 +14,7 @@ module ActiveModel
@first_comment.post = @post @first_comment.post = @post
@second_comment.post = @post @second_comment.post = @post
@post.author = @author @post.author = @author
@blog = Blog.new(id: 1, name: "My Blog!!") @blog = Blog.new(id: 1, name: 'My Blog!!')
@post.blog = @blog @post.blog = @blog
@serializer = PostSerializer.new(@post) @serializer = PostSerializer.new(@post)
@ -34,11 +34,11 @@ module ActiveModel
assert_equal({ assert_equal({
id: 1, id: 1,
reviews: [{id: 1, body: "ZOMG A COMMENT"}, reviews: [{ 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

View File

@ -15,6 +15,10 @@ module ActiveModel
resource resource
end end
def test_has_object_reader_serializer_interface
assert_equal @serializer.object, @resource
end
def test_respond_to_each def test_respond_to_each
assert_respond_to @serializer, :each assert_respond_to @serializer, :each
end end
@ -38,11 +42,11 @@ module ActiveModel
end end
def test_meta_and_meta_key_attr_readers def test_meta_and_meta_key_attr_readers
meta_content = {meta: "the meta", meta_key: "the meta key"} meta_content = { meta: 'the meta', meta_key: 'the meta key' }
@serializer = ArraySerializer.new([@comment, @post], meta_content) @serializer = ArraySerializer.new([@comment, @post], meta_content)
assert_equal @serializer.meta, "the meta" assert_equal @serializer.meta, 'the meta'
assert_equal @serializer.meta_key, "the meta key" assert_equal @serializer.meta_key, 'the meta key'
end end
def test_root_default def test_root_default

View File

@ -1,15 +1,15 @@
# https://raw.githubusercontent.com/metric_fu/metric_fu/master/spec/capture_warnings.rb # https://raw.githubusercontent.com/metric_fu/metric_fu/master/spec/capture_warnings.rb
require "tempfile" require 'tempfile'
require "fileutils" require 'fileutils'
class CaptureWarnings class CaptureWarnings
def initialize(fail_on_warnings = true) def initialize(fail_on_warnings = true)
@fail_on_warnings = fail_on_warnings @fail_on_warnings = fail_on_warnings
@stderr_file = Tempfile.new("app.stderr") @stderr_file = Tempfile.new('app.stderr')
@app_root ||= Dir.pwd @app_root ||= Dir.pwd
@output_dir = File.join(app_root, "tmp") @output_dir = File.join(app_root, 'tmp')
FileUtils.mkdir_p(output_dir) FileUtils.mkdir_p(output_dir)
@bundle_dir = File.join(app_root, "bundle") @bundle_dir = File.join(app_root, 'bundle')
end end
def before_tests def before_tests
@ -40,9 +40,9 @@ class CaptureWarnings
end end
if other_warnings.any? if other_warnings.any?
File.write(File.join(output_dir, "warnings.txt"), other_warnings.join("\n") << "\n") File.write(File.join(output_dir, 'warnings.txt'), other_warnings.join("\n") << "\n")
puts puts
puts "Non-app warnings written to tmp/warnings.txt" puts 'Non-app warnings written to tmp/warnings.txt'
puts puts
end end
@ -53,5 +53,6 @@ class CaptureWarnings
end end
private private
attr_reader :stderr_file, :app_root, :output_dir, :bundle_dir, :fail_on_warnings attr_reader :stderr_file, :app_root, :output_dir, :bundle_dir, :fail_on_warnings
end end

57
test/fixtures/active_record.rb vendored Normal file
View File

@ -0,0 +1,57 @@
require 'active_record'
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
ActiveRecord::Schema.define do
create_table :posts, force: true do |t|
t.string :title
t.text :body
t.references :author
t.timestamps null: false
end
create_table :authors, force: true do |t|
t.string :name
t.timestamps null: false
end
create_table :comments, force: true do |t|
t.text :contents
t.references :author
t.references :post
t.timestamp null: false
end
end
module ARModels
class Post < ActiveRecord::Base
has_many :comments
belongs_to :author
end
class Comment < ActiveRecord::Base
belongs_to :post
belongs_to :author
end
class Author < ActiveRecord::Base
has_many :posts
end
class PostSerializer < ActiveModel::Serializer
attributes :id, :title, :body
has_many :comments
belongs_to :author
url :comments
end
class CommentSerializer < ActiveModel::Serializer
attributes :id, :contents
belongs_to :author
end
class AuthorSerializer < ActiveModel::Serializer
attributes :id, :name
has_many :posts
end
end

View File

@ -103,7 +103,7 @@ PostSerializer = Class.new(ActiveModel::Serializer) do
url :comments url :comments
def blog def blog
Blog.new(id: 999, name: "Custom blog") Blog.new(id: 999, name: 'Custom blog')
end end
def custom_options def custom_options
@ -134,10 +134,11 @@ end
AuthorSerializer = Class.new(ActiveModel::Serializer) do AuthorSerializer = Class.new(ActiveModel::Serializer) do
cache key: 'writer', skip_digest: true cache key: 'writer', skip_digest: true
attributes :id, :name attribute :id
attribute :name
has_many :posts, embed: :ids has_many :posts
has_many :roles, embed: :ids has_many :roles
has_one :bio has_one :bio
end end

View File

@ -1,5 +1,4 @@
require 'test_helper' require 'test_helper'
# require 'active_model/serializer/railtie'
class ResourceGeneratorTest < Rails::Generators::TestCase class ResourceGeneratorTest < Rails::Generators::TestCase
destination File.expand_path('../../../tmp/generators', __FILE__) destination File.expand_path('../../../tmp/generators', __FILE__)

View File

@ -2,7 +2,7 @@ require 'test_helper'
require 'generators/serializer/serializer_generator' require 'generators/serializer/serializer_generator'
class SerializerGeneratorTest < Rails::Generators::TestCase class SerializerGeneratorTest < Rails::Generators::TestCase
destination File.expand_path("../../../tmp/generators", __FILE__) destination File.expand_path('../../../tmp/generators', __FILE__)
setup :prepare_destination setup :prepare_destination
tests Rails::Generators::SerializerGenerator tests Rails::Generators::SerializerGenerator
@ -10,33 +10,33 @@ class SerializerGeneratorTest < Rails::Generators::TestCase
def test_generates_a_serializer def test_generates_a_serializer
run_generator run_generator
assert_file "app/serializers/account_serializer.rb", /class AccountSerializer < ActiveModel::Serializer/ assert_file 'app/serializers/account_serializer.rb', /class AccountSerializer < ActiveModel::Serializer/
end end
def test_generates_a_namespaced_serializer def test_generates_a_namespaced_serializer
run_generator ["admin/account"] run_generator ['admin/account']
assert_file "app/serializers/admin/account_serializer.rb", /class Admin::AccountSerializer < ActiveModel::Serializer/ assert_file 'app/serializers/admin/account_serializer.rb', /class Admin::AccountSerializer < ActiveModel::Serializer/
end end
def test_uses_application_serializer_if_one_exists def test_uses_application_serializer_if_one_exists
Object.const_set(:ApplicationSerializer, Class.new) Object.const_set(:ApplicationSerializer, Class.new)
run_generator run_generator
assert_file "app/serializers/account_serializer.rb", /class AccountSerializer < ApplicationSerializer/ assert_file 'app/serializers/account_serializer.rb', /class AccountSerializer < ApplicationSerializer/
ensure ensure
Object.send :remove_const, :ApplicationSerializer Object.send :remove_const, :ApplicationSerializer
end end
def test_uses_given_parent def test_uses_given_parent
Object.const_set(:ApplicationSerializer, Class.new) Object.const_set(:ApplicationSerializer, Class.new)
run_generator ["Account", "--parent=MySerializer"] run_generator ['Account', '--parent=MySerializer']
assert_file "app/serializers/account_serializer.rb", /class AccountSerializer < MySerializer/ assert_file 'app/serializers/account_serializer.rb', /class AccountSerializer < MySerializer/
ensure ensure
Object.send :remove_const, :ApplicationSerializer Object.send :remove_const, :ApplicationSerializer
end end
def test_generates_attributes_and_associations def test_generates_attributes_and_associations
run_generator run_generator
assert_file "app/serializers/account_serializer.rb" do |serializer| assert_file 'app/serializers/account_serializer.rb' do |serializer|
assert_match(/^ attributes :id, :name, :description$/, serializer) assert_match(/^ attributes :id, :name, :description$/, serializer)
assert_match(/^ has_one :business$/, serializer) assert_match(/^ has_one :business$/, serializer)
assert_match(/^end\n*\z/, serializer) assert_match(/^end\n*\z/, serializer)
@ -44,8 +44,8 @@ class SerializerGeneratorTest < Rails::Generators::TestCase
end end
def test_with_no_attributes_does_not_add_extra_space def test_with_no_attributes_does_not_add_extra_space
run_generator ["account"] run_generator ['account']
assert_file "app/serializers/account_serializer.rb" do |content| assert_file 'app/serializers/account_serializer.rb' do |content|
if RUBY_PLATFORM =~ /mingw/ if RUBY_PLATFORM =~ /mingw/
assert_no_match(/\r\n\r\nend/, content) assert_no_match(/\r\n\r\nend/, content)
else else

View File

@ -7,27 +7,21 @@ module ActiveModel
class CompliantResource class CompliantResource
def serializable_hash(options = nil) def serializable_hash(options = nil)
end end
def read_attribute_for_serialization(name) def read_attribute_for_serialization(name)
end end
def as_json(options = nil) def as_json(options = nil)
end end
def to_json(options = nil) def to_json(options = nil)
end end
def cache_key def cache_key
end end
def id def id
end end
def self.model_name def self.model_name
@ -38,7 +32,6 @@ module ActiveModel
def setup def setup
@resource = CompliantResource.new @resource = CompliantResource.new
end end
end end
end end
end end

View File

@ -20,7 +20,6 @@ module ActiveModel
adapter = ActiveModel::Serializer.adapter adapter = ActiveModel::Serializer.adapter
assert_equal ActiveModel::Serializer::Adapter::Null, adapter assert_equal ActiveModel::Serializer::Adapter::Null, adapter
ensure ensure
end end
def test_overwrite_adapter_with_class def test_overwrite_adapter_with_class

View File

@ -6,7 +6,7 @@ module ActiveModel
AuthorSummarySerializer = Class.new AuthorSummarySerializer = Class.new
class AssociationsTestSerializer < Serializer class AssociationsTestSerializer < Serializer
belongs_to :author, serializer: AuthorSummarySerializer belongs_to :author, serializer: AuthorSummarySerializer
has_many :comments, embed: :ids has_many :comments
has_one :category has_one :category
end end
@ -21,7 +21,7 @@ module ActiveModel
end end
def test_has_many_defines_reflection def test_has_many_defines_reflection
has_many_reflection = HasManyReflection.new(:comments, embed: :ids) has_many_reflection = HasManyReflection.new(:comments, {})
assert_includes(@reflections, has_many_reflection) assert_includes(@reflections, has_many_reflection)
end end

View File

@ -52,13 +52,13 @@ module ActiveModel
case key case key
when :posts when :posts
assert_equal({ embed: :ids }, options) assert_equal({}, options)
assert_kind_of(ActiveModel::Serializer.config.array_serializer, serializer) assert_kind_of(ActiveModel::Serializer.config.array_serializer, serializer)
when :bio when :bio
assert_equal({}, options) assert_equal({}, options)
assert_nil serializer assert_nil serializer
when :roles when :roles
assert_equal({ embed: :ids }, options) assert_equal({}, options)
assert_kind_of(ActiveModel::Serializer.config.array_serializer, serializer) assert_kind_of(ActiveModel::Serializer.config.array_serializer, serializer)
else else
flunk "Unknown association: #{key}" flunk "Unknown association: #{key}"
@ -74,7 +74,7 @@ module ActiveModel
assert_equal key, :tags assert_equal key, :tags
assert_equal serializer, nil assert_equal serializer, nil
assert_equal [{ attributes: { name: "#hashtagged" }}].to_json, options[:virtual_value].to_json assert_equal [{ attributes: { name: '#hashtagged' } }].to_json, options[:virtual_value].to_json
end end
end end

View File

@ -4,7 +4,7 @@ module ActiveModel
class Serializer class Serializer
class AttributeTest < Minitest::Test class AttributeTest < Minitest::Test
def setup def setup
@blog = Blog.new({ id: 1, name: 'AMS Hints', type: "stuff" }) @blog = Blog.new({ id: 1, name: 'AMS Hints', type: 'stuff' })
@blog_serializer = AlternateBlogSerializer.new(@blog) @blog_serializer = AlternateBlogSerializer.new(@blog)
end end
@ -15,14 +15,14 @@ module ActiveModel
def test_json_serializable_hash def test_json_serializable_hash
adapter = ActiveModel::Serializer::Adapter::Json.new(@blog_serializer) adapter = ActiveModel::Serializer::Adapter::Json.new(@blog_serializer)
assert_equal({blog: { id:1, title:"AMS Hints"}}, adapter.serializable_hash) assert_equal({ blog: { id: 1, title: 'AMS Hints' } }, adapter.serializable_hash)
end end
def test_attribute_inheritance_with_key def test_attribute_inheritance_with_key
inherited_klass = Class.new(AlternateBlogSerializer) inherited_klass = Class.new(AlternateBlogSerializer)
blog_serializer = inherited_klass.new(@blog) blog_serializer = inherited_klass.new(@blog)
adapter = ActiveModel::Serializer::Adapter::FlattenJson.new(blog_serializer) adapter = ActiveModel::Serializer::Adapter::FlattenJson.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
@ -40,7 +40,7 @@ module ActiveModel
end end
adapter = ActiveModel::Serializer::Adapter::Json.new(serializer.new(@blog)) adapter = ActiveModel::Serializer::Adapter::Json.new(serializer.new(@blog))
assert_equal({ blog: { id: "AMS Hints" } }, adapter.serializable_hash) assert_equal({ blog: { id: 'AMS Hints' } }, adapter.serializable_hash)
end end
def test_type_attribute def test_type_attribute
@ -55,7 +55,7 @@ module ActiveModel
assert_equal({ blog: { type: 1 } }, adapter.serializable_hash) assert_equal({ blog: { type: 1 } }, adapter.serializable_hash)
adapter = ActiveModel::Serializer::Adapter::Json.new(attributes_serializer.new(@blog)) adapter = ActiveModel::Serializer::Adapter::Json.new(attributes_serializer.new(@blog))
assert_equal({ blog: { type: "stuff" } }, adapter.serializable_hash) assert_equal({ blog: { type: 'stuff' } }, adapter.serializable_hash)
end end
end end
end end

View File

@ -6,7 +6,7 @@ module ActiveModel
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)
@serializer_klass_with_new_attributes = Class.new(CommentSerializer) do @serializer_klass_with_new_attributes = Class.new(CommentSerializer) do
attributes :date, :likes attributes :date, :likes
@ -29,7 +29,7 @@ module ActiveModel
def test_attributes_inheritance def test_attributes_inheritance
serializer = @serializer_klass.new(@comment) serializer = @serializer_klass.new(@comment)
assert_equal({id: 1, body: "ZOMG!!"}, assert_equal({ id: 1, body: 'ZOMG!!' },
serializer.attributes) serializer.attributes)
end end
@ -40,7 +40,7 @@ module ActiveModel
def test_attribute_inheritance_with_new_attribute def test_attribute_inheritance_with_new_attribute
serializer = @serializer_klass_with_new_attributes.new(@comment) serializer = @serializer_klass_with_new_attributes.new(@comment)
assert_equal({id: 1, body: "ZOMG!!", date: "2015", likes: nil}, assert_equal({ id: 1, body: 'ZOMG!!', date: '2015', likes: nil },
serializer.attributes) serializer.attributes)
end end

View File

@ -9,7 +9,7 @@ module ActiveModel
@post = Post.new(title: 'New Post', body: 'Body') @post = Post.new(title: 'New Post', body: 'Body')
@bio = Bio.new(id: 1, content: 'AMS Contributor') @bio = Bio.new(id: 1, content: 'AMS Contributor')
@author = Author.new(name: 'Joao M. D. Moura') @author = Author.new(name: 'Joao M. D. Moura')
@blog = Blog.new(id: 999, name: "Custom blog", writer: @author, articles: []) @blog = Blog.new(id: 999, name: 'Custom blog', writer: @author, articles: [])
@role = Role.new(name: 'Great Author') @role = Role.new(name: 'Great Author')
@location = Location.new(lat: '-23.550520', lng: '-46.633309') @location = Location.new(lat: '-23.550520', lng: '-46.633309')
@place = Place.new(name: 'Amazing Place') @place = Place.new(name: 'Amazing Place')
@ -131,20 +131,20 @@ module ActiveModel
end end
def test_serializer_file_path_on_nix def test_serializer_file_path_on_nix
path = "/Users/git/emberjs/ember-crm-backend/app/serializers/lead_serializer.rb" path = '/Users/git/emberjs/ember-crm-backend/app/serializers/lead_serializer.rb'
caller_line = "#{path}:1:in `<top (required)>'" caller_line = "#{path}:1:in `<top (required)>'"
assert_equal caller_line[ActiveModel::Serializer::CALLER_FILE], path assert_equal caller_line[ActiveModel::Serializer::CALLER_FILE], path
end end
def test_serializer_file_path_on_windows def test_serializer_file_path_on_windows
path = "c:/git/emberjs/ember-crm-backend/app/serializers/lead_serializer.rb" path = 'c:/git/emberjs/ember-crm-backend/app/serializers/lead_serializer.rb'
caller_line = "#{path}:1:in `<top (required)>'" caller_line = "#{path}:1:in `<top (required)>'"
assert_equal caller_line[ActiveModel::Serializer::CALLER_FILE], path assert_equal caller_line[ActiveModel::Serializer::CALLER_FILE], path
end end
def test_digest_caller_file def test_digest_caller_file
contents = "puts 'AMS rocks'!" contents = "puts 'AMS rocks'!"
file = Tempfile.new("some_ruby.rb") file = Tempfile.new('some_ruby.rb')
file.write(contents) file.write(contents)
path = file.path path = file.path
caller_line = "#{path}:1:in `<top (required)>'" caller_line = "#{path}:1:in `<top (required)>'"
@ -155,6 +155,7 @@ module ActiveModel
end end
private private
def render_object_with_cache(obj) def render_object_with_cache(obj)
ActiveModel::SerializableResource.new(obj).serializable_hash ActiveModel::SerializableResource.new(obj).serializable_hash
end end

View File

@ -3,9 +3,8 @@ require 'test_helper'
module ActiveModel module ActiveModel
class Serializer class Serializer
class FieldsetTest < Minitest::Test class FieldsetTest < Minitest::Test
def test_fieldset_with_hash def test_fieldset_with_hash
fieldset = ActiveModel::Serializer::Fieldset.new({'post' => ['id', 'title'], 'coment' => ['body']}) fieldset = ActiveModel::Serializer::Fieldset.new({ 'post' => %w(id title), 'coment' => ['body'] })
assert_equal( assert_equal(
{ :post => [:id, :title], :coment => [:body] }, { :post => [:id, :title], :coment => [:body] },

View File

@ -7,8 +7,8 @@ module ActiveModel
ActionController::Base.cache_store.clear ActionController::Base.cache_store.clear
@blog = Blog.new(id: 1, @blog = Blog.new(id: 1,
name: 'AMS Hints', name: 'AMS Hints',
writer: Author.new(id: 2, name: "Steve"), writer: Author.new(id: 2, name: 'Steve'),
articles: [Post.new(id: 3, title: "AMS")]) articles: [Post.new(id: 3, title: 'AMS')])
end end
def test_meta_is_present_with_root def test_meta_is_present_with_root
@ -17,9 +17,9 @@ module ActiveModel
expected = { expected = {
blog: { blog: {
id: 1, id: 1,
title: "AMS Hints" title: 'AMS Hints'
}, },
"meta" => { 'meta' => {
total: 10 total: 10
} }
} }
@ -31,20 +31,20 @@ module ActiveModel
adapter = load_adapter(meta: { total: 10 }) adapter = load_adapter(meta: { total: 10 })
expected = { expected = {
id: 1, id: 1,
title: "AMS Hints" title: 'AMS Hints'
} }
assert_equal expected, adapter.as_json assert_equal expected, adapter.as_json
end end
def test_meta_key_is_used def test_meta_key_is_used
serializer = AlternateBlogSerializer.new(@blog, meta: {total: 10}, meta_key: "haha_meta") serializer = AlternateBlogSerializer.new(@blog, meta: { total: 10 }, meta_key: 'haha_meta')
adapter = ActiveModel::Serializer::Adapter::Json.new(serializer) adapter = ActiveModel::Serializer::Adapter::Json.new(serializer)
expected = { expected = {
blog: { blog: {
id: 1, id: 1,
title: "AMS Hints" title: 'AMS Hints'
}, },
"haha_meta" => { 'haha_meta' => {
total: 10 total: 10
} }
} }
@ -52,15 +52,15 @@ module ActiveModel
end end
def test_meta_key_is_used_with_json_api def test_meta_key_is_used_with_json_api
serializer = AlternateBlogSerializer.new(@blog, meta: {total: 10}, meta_key: "haha_meta") serializer = AlternateBlogSerializer.new(@blog, meta: { total: 10 }, meta_key: 'haha_meta')
adapter = ActiveModel::Serializer::Adapter::JsonApi.new(serializer) adapter = ActiveModel::Serializer::Adapter::JsonApi.new(serializer)
expected = { expected = {
data: { data: {
id: "1", id: '1',
type: "blogs", type: 'blogs',
attributes: { title: "AMS Hints" } attributes: { title: 'AMS Hints' }
}, },
"haha_meta" => { total: 10 } 'haha_meta' => { total: 10 }
} }
assert_equal expected, adapter.as_json assert_equal expected, adapter.as_json
end end
@ -71,14 +71,14 @@ module ActiveModel
adapter = ActiveModel::Serializer::Adapter::FlattenJson.new(serializer) adapter = ActiveModel::Serializer::Adapter::FlattenJson.new(serializer)
expected = [{ expected = [{
id: 1, id: 1,
name: "AMS Hints", name: 'AMS Hints',
writer: { writer: {
id: 2, id: 2,
name: "Steve" name: 'Steve'
}, },
articles: [{ articles: [{
id: 3, id: 3,
title: "AMS", title: 'AMS',
body: nil body: nil
}] }]
}] }]
@ -86,20 +86,20 @@ module ActiveModel
end end
def test_meta_is_present_on_arrays_with_root def test_meta_is_present_on_arrays_with_root
serializer = ArraySerializer.new([@blog], meta: {total: 10}, meta_key: "haha_meta") serializer = ArraySerializer.new([@blog], meta: { total: 10 }, meta_key: 'haha_meta')
# JSON adapter adds root by default # JSON adapter adds root by default
adapter = ActiveModel::Serializer::Adapter::Json.new(serializer) adapter = ActiveModel::Serializer::Adapter::Json.new(serializer)
expected = { expected = {
blogs: [{ blogs: [{
id: 1, id: 1,
name: "AMS Hints", name: 'AMS Hints',
writer: { writer: {
id: 2, id: 2,
name: "Steve" name: 'Steve'
}, },
articles: [{ articles: [{
id: 3, id: 3,
title: "AMS", title: 'AMS',
body: nil body: nil
}] }]
}], }],

View File

@ -3,7 +3,6 @@ require 'test_helper'
module ActiveModel module ActiveModel
class Serializer class Serializer
class RootTest < Minitest::Test class RootTest < Minitest::Test
def setup def setup
@virtual_value = VirtualValue.new(id: 1) @virtual_value = VirtualValue.new(id: 1)
end end
@ -17,7 +16,6 @@ module ActiveModel
serializer = VirtualValueSerializer.new(@virtual_value) serializer = VirtualValueSerializer.new(@virtual_value)
assert_equal('virtual_value', serializer.json_key) assert_equal('virtual_value', serializer.json_key)
end end
end end
end end
end end

View File

@ -3,7 +3,6 @@ require 'test_helper'
module ActiveModel module ActiveModel
class Serializer class Serializer
class UrlsTest < Minitest::Test class UrlsTest < Minitest::Test
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' })
@post = Post.new({ title: 'New Post', body: 'Body' }) @post = Post.new({ title: 'New Post', body: 'Body' })

View File

@ -1,7 +1,7 @@
# Use cleaner stream testing interface from Rails 5 if available # Use cleaner stream testing interface from Rails 5 if available
# see https://github.com/rails/rails/blob/29959eb59d/activesupport/lib/active_support/testing/stream.rb # see https://github.com/rails/rails/blob/29959eb59d/activesupport/lib/active_support/testing/stream.rb
begin begin
require "active_support/testing/stream" require 'active_support/testing/stream'
rescue LoadError rescue LoadError
module ActiveSupport module ActiveSupport
module Testing module Testing
@ -29,7 +29,7 @@ rescue LoadError
def capture(stream) def capture(stream)
stream = stream.to_s stream = stream.to_s
captured_stream = Tempfile.new(stream) captured_stream = Tempfile.new(stream)
stream_io = eval("$#{stream}") stream_io = eval("$#{stream}") # rubocop:disable Lint/Eval
origin_stream = stream_io.dup origin_stream = stream_io.dup
stream_io.reopen(captured_stream) stream_io.reopen(captured_stream)

View File

@ -13,7 +13,6 @@ require 'minitest/autorun'
# Ensure backward compatibility with Minitest 4 # Ensure backward compatibility with Minitest 4
Minitest::Test = MiniTest::Unit::TestCase unless defined?(Minitest::Test) Minitest::Test = MiniTest::Unit::TestCase unless defined?(Minitest::Test)
require 'capture_warnings' require 'capture_warnings'
@capture_warnings = CaptureWarnings.new(fail_build = true) @capture_warnings = CaptureWarnings.new(fail_build = true)
@capture_warnings.before_tests @capture_warnings.before_tests
@ -23,7 +22,7 @@ if Minitest.respond_to?(:after_run)
end end
else else
at_exit do at_exit do
STDOUT.puts "Minitest.after_run not available." STDOUT.puts 'Minitest.after_run not available.'
@capture_warnings.after_tests @capture_warnings.after_tests
end end
end end
@ -34,6 +33,8 @@ require 'support/stream_capture'
require 'support/rails_app' require 'support/rails_app'
require 'fixtures/poro'
require 'support/test_case' require 'support/test_case'
require 'fixtures/active_record'
require 'fixtures/poro'