-
Notifications
You must be signed in to change notification settings - Fork 0
Description
I want to use duck-typing to simplify the call chain of Transmutation::Serializer#as_json.
Context
The current code for Transmutation::Serializer#as_json looks like:
def as_json(options = {})
attributes_config.each_with_object({}) do |(attr_name, attr_options), hash|
if attr_options[:association]
hash[attr_name.to_s] = instance_exec(&attr_options[:block]).as_json(options) if @depth + 1 <= @max_depth
else
hash[attr_name.to_s] = attr_options[:block] ? instance_exec(&attr_options[:block]) : object.send(attr_name)
end
end
endThere are 2 conditionals here that I would like to abstract away.
-
if attr_options[:association]I want to define
AttributeandAssociationclasses that respond to#as_json. This encapsulates the individual and distinct serialization logic of attributes vs associations. -
attr_options[:block] ? instance_exec(&attr_options[:block]) : object.send(attr_name)Following the line of thought from 2), calling
Attribute#as_jsonshould perform this line of logic.
Once both changes have been implemented, the Transmutation::Serializer#as_json method definition can be simplified down to something along the lines of:
def as_json(options = {})
fields.each_with_object({}) do |field, hash|
hash[field.name] = field.as_json if @depth + 1 <= @max_depth
end
end