Clean up notification code with some meta-prog

This commit is contained in:
Benjamin Fleischer 2015-11-08 15:49:50 -06:00
parent 21bb306d38
commit 360ecc88fe
5 changed files with 39 additions and 28 deletions

View File

@ -31,8 +31,7 @@ module ActionController
serializable_resource.serialization_scope ||= serialization_scope
serializable_resource.serialization_scope_name = _serialization_scope
begin
serializable_resource.adapter
serializable_resource
serializable_resource.tap(&:adapter)
rescue ActiveModel::Serializer::CollectionSerializer::NoSerializerError
resource
end

View File

@ -4,6 +4,11 @@ module ActiveModel
ADAPTER_OPTION_KEYS = Set.new([:include, :fields, :adapter, :meta, :meta_key, :links])
include ActiveModelSerializers::Logging
delegate :serializable_hash, :as_json, :to_json, to: :adapter
notify :serializable_hash, :render
notify :as_json, :render
notify :to_json, :render
# Primary interface to composing a resource with a serializer and adapter.
# @return the serializable_resource, ready for #as_json/#to_json/#serializable_hash.
def initialize(resource, options = {})
@ -12,24 +17,6 @@ module ActiveModel
options.partition { |k, _| ADAPTER_OPTION_KEYS.include? k }.map { |h| Hash[h] }
end
def serializable_hash(*args)
run_callbacks :render do
adapter.serializable_hash(*args)
end
end
def as_json(*args)
run_callbacks :render do
adapter.as_json(*args)
end
end
def to_json(*args)
run_callbacks :render do
adapter.to_json(*args)
end
end
def serialization_scope=(scope)
serializer_opts[:scope] = scope
end

View File

@ -1,4 +1,3 @@
require 'active_model_serializers'
require 'rails/railtie'
module ActiveModel

View File

@ -2,14 +2,39 @@
# Adapted from:
# https://github.com/rails/rails/blob/280654ef88/activejob/lib/active_job/logging.rb
module ActiveModelSerializers::Logging
extend ActiveSupport::Concern
def self.included(base)
base.send(:include, ActiveSupport::Callbacks)
base.extend ClassMethods
base.class_eval do
define_callbacks :render
around_render do |_, block|
notify_active_support do
block.call
end
end
end
end
included do
extend ActiveModel::Callbacks
define_model_callbacks :render
around_render do |_, block, _|
notify_active_support do
block.call
module ClassMethods
def around_render(*filters, &blk)
set_callback(:render, :around, *filters, &blk)
end
##
# Simple notify method that wraps up +name+
# in a dummy method. It notifies on each call to the dummy method
# telling what the current serializer and adapter are being rendered.
# Adapted from:
# https://github.com/rubygems/rubygems/blob/cb28f5e991/lib/rubygems/deprecate.rb
def notify(name, callback_name)
class_eval do
old = "_notifying_#{callback_name}_#{name}"
alias_method old, name
define_method name do |*args, &block|
run_callbacks callback_name do
send old, *args, &block
end
end
end
end
end

View File

@ -50,6 +50,7 @@ if ENV['CAPTURE_STDERR'] !~ /false|1/i
end
require 'active_model_serializers'
require 'active_model/serializer/railtie'
require 'support/stream_capture'