Skip to content

Commit

Permalink
refactored a bit more, and matched some method names to that of json_api
Browse files Browse the repository at this point in the history
  • Loading branch information
NullVoxPopuli committed Aug 31, 2015
1 parent 5b33c44 commit 081b504
Showing 1 changed file with 43 additions and 21 deletions.
64 changes: 43 additions & 21 deletions lib/active_model/serializer/adapter/json.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,51 +11,73 @@ def serializable_hash(options = nil)
else
@hash = {}

@core = serialized_attributes_of(serializer, options)
@core = resource_object_for(serializer, options)

serializer.associations.each do |association|
serializer = association.serializer
opts = association.options
add_resource_relationships(serializer)

if serializer.respond_to?(:each)
@hash[association.key] = serialize_array(serializer, opts)
else
@hash[association.key] = serialized_or_virtual_of(serializer, opts)
end
end
@result = @core.merge @hash
end

{ root => @result }
end

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

private

# iterate through the associations on the serializer,
# adding them to @hash as needed (as singular or plural)
def add_resource_relationships(serializer)
serializer.associations.each do |association|
serializer = association.serializer
opts = association.options

if serializer.respond_to?(:each)
add_relationships(association.key, serializer, opts)
else
add_relationship(association.key, serializer, opts)
end
end

@hash
end

# add a singular relationship
def add_relationship(key, serializer, options)
@hash[key] = serialized_or_virtual_of(serializer, options)
end

# add a many relationship
def add_relationships(key, serializer, options)
@hash[key] = serialize_array(serializer, options)
end

def serialize_array_without_root(serializer, options)
serializer.map { |s| FlattenJson.new(s).serializable_hash(options) }
end

# TODO: what is a virtual value?
# a virtual value is something that doesn't need a serializer,
# such as a ruby array, or any other raw value
def serialized_or_virtual_of(serializer, options)
if serializer && serializer.object
serialized_attributes_of(serializer, options)
resource_object_for(serializer, options)
elsif options[:virtual_value]
options[:virtual_value]
end
end

def serialized_attributes_of(item, options)
cache_check(item) do
item.attributes(options)
end
end

def serialize_array(serializer, options)
serializer.map do |item|
serialized_attributes_of(item, options)
resource_object_for(item, options)
end
end

def fragment_cache(cached_hash, non_cached_hash)
Json::FragmentCache.new().fragment_cache(cached_hash, non_cached_hash)
def resource_object_for(item, options)
cache_check(item) do
item.attributes(options)
end
end

end
Expand Down

0 comments on commit 081b504

Please sign in to comment.