Skip to content

Use duck-typing to avoid conditional between attributes and associations #23

Description

@Nitemaeric

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
end

There are 2 conditionals here that I would like to abstract away.

  1. if attr_options[:association]

    I want to define Attribute and Association classes that respond to #as_json. This encapsulates the individual and distinct serialization logic of attributes vs associations.

  2. attr_options[:block] ? instance_exec(&attr_options[:block]) : object.send(attr_name)

    Following the line of thought from 2), calling Attribute#as_json should 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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions