Skip to content

Commit

Permalink
Refactor NestedJson adapter.
Browse files Browse the repository at this point in the history
  • Loading branch information
kayhide committed Aug 26, 2015
1 parent e6d6c5e commit 0e43a6e
Showing 1 changed file with 36 additions and 30 deletions.
66 changes: 36 additions & 30 deletions lib/active_model/serializer/adapter/nested_json.rb
Original file line number Diff line number Diff line change
@@ -1,54 +1,60 @@
module ActiveModel
class Serializer
class Adapter
class NestedJson < Json
class NestedJson < Adapter
cattr_accessor :default_limit_depth
@@default_limit_depth = 5
self.default_limit_depth = 5

def serializable_hash options = {}
@current_depth = options[:_current_depth] || 0
@limit_depth = options[:limit_depth] || default_limit_depth
check_depth!

if serializer.respond_to?(:each)
@result = serialize_collection(serializer, options)
else
@hash = {}

@core = cache_check(serializer) do
serializer.attributes(options)
end

serializer.associations.each do |association|
serializer = association.serializer
opts = association.options

if serializer.respond_to?(:each)
@hash[association.key] = serialize_collection(serializer, opts)
elsif serializer && serializer.object
@hash[association.key] = serialize_object(serializer, opts)
else
@hash[association.key] = opts[:virtual_value]
end
end
@result = @core.merge @hash
end
@result =
serialize_collection(serializer, options) ||
serialize_attributes(options).merge(serialize_associations)
end

@result
def fragment_cache(cached_hash, non_cached_hash)
Json::FragmentCache.new().fragment_cache(cached_hash, non_cached_hash)
end

private
def serialize_object serializer, options = {}
options = options.merge(_current_depth: @current_depth + 1, limit_depth: @limit_depth)
self.class.new(serializer).serializable_hash(options)
if serializer.try(:object)
options = options.merge(_current_depth: @current_depth + 1, limit_depth: @limit_depth)
self.class.new(serializer).serializable_hash(options)
end
end

def serialize_collection serializers, options = {}
serializers.map { |s| serialize_object(s, options) }
if serializers.respond_to?(:each)
serializers.map { |s| serialize_object(s, options) }
end
end

def serialize_attributes options
cache_check(serializer) do
serializer.attributes(options)
end
end

def serialize_associations
hash = {}
serializer.associations.each do |association|
serializer = association.serializer
opts = association.options
hash[association.key] =
serialize_collection(serializer, opts) ||
serialize_object(serializer, opts) ||
opts[:virtual_value]
end
hash
end

def check_depth!
if @current_depth > @limit_depth
fail "associations are too deep."
fail 'Too deep associations.'
end
end
end
Expand Down

0 comments on commit 0e43a6e

Please sign in to comment.