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

Fix code-styling issues from .rubocop_todo.yml

* re: RuboCop: Bulk minor style corrections

* re: RuboCop - hash indention corrections

* re: RuboCop - replace rocket style hashes

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

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

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

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

* re: RuboCop - use include_ prefix instead of has_

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

* re: RuboCop - Remove empty .rubocop_todo.yml

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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