Skip to content

Commit

Permalink
Serializer#serializer_from_options refactoring and small changes in S…
Browse files Browse the repository at this point in the history
…erializer#associations
  • Loading branch information
Dmitriy Myaskovskiy committed Jul 6, 2015
1 parent 7b27cc2 commit 9b59060
Showing 1 changed file with 12 additions and 10 deletions.
22 changes: 12 additions & 10 deletions lib/active_model/serializer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -220,24 +220,25 @@ def associations
self.class._reflections.dup.each do |reflection|
name = reflection.name
association_value = send(name)
serializer_class = ActiveModel::Serializer.serializer_for(association_value, reflection.options)
reflection_options = reflection.options.dup
serializer_class = ActiveModel::Serializer.serializer_for(association_value, reflection_options)

if serializer_class
begin
serializer = serializer_class.new(
association_value,
options.except(:serializer).merge(serializer_from_options(reflection.options))
serializer_options(reflection_options)
)
rescue ActiveModel::Serializer::ArraySerializer::NoSerializerError
virtual_value = association_value
virtual_value = virtual_value.as_json if virtual_value.respond_to?(:as_json)
reflection.options[:virtual_value] = virtual_value
reflection_options[:virtual_value] = virtual_value
end
elsif !association_value.nil? && !association_value.instance_of?(Object)
reflection.options[:virtual_value] = association_value
reflection_options[:virtual_value] = association_value
end

y.yield Association.new(name, serializer, reflection.options)
y.yield Association.new(name, serializer, reflection_options)
end
end
end
Expand All @@ -248,11 +249,12 @@ def self.serializers_cache

private

def serializer_from_options(options)
opts = {}
serializer = options.fetch(:serializer, nil)
opts[:serializer] = serializer if serializer
opts
def serializer_options(reflection_options)
serializer = reflection_options.fetch(:serializer, nil)

serializer_options = options.except(:serializer)
serializer_options[:serializer] = serializer if serializer
serializer_options
end

attr_reader :options
Expand Down

0 comments on commit 9b59060

Please sign in to comment.