Skip to content

Commit

Permalink
Clean up notification code with some meta-prog
Browse files Browse the repository at this point in the history
  • Loading branch information
bf4 committed Nov 8, 2015
1 parent fdacb0b commit 600974d
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 18 deletions.
23 changes: 5 additions & 18 deletions lib/active_model/serializable_resource.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ class SerializableResource
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 = {})
Expand All @@ -12,24 +17,6 @@ def initialize(resource, options = {})
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
Expand Down
21 changes: 21 additions & 0 deletions lib/active_model_serializers/logging.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,27 @@ module ActiveModelSerializers::Logging
end
end

class_methods do
##
# 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

def notify_active_support
event_name = 'render.active_model_serializers'.freeze
payload = { serializer: serializer, adapter: adapter }
Expand Down

0 comments on commit 600974d

Please sign in to comment.