Startouf
10/25/2018 - 10:13 PM

jsonapi_suite sideloading of in-memory associations

jsonapi_suite sideloading of in-memory associations

# In-memory associations as jsonapi_suite sideloads
# Using the trick of memoization, assuming the parent known about the children
# 
# @example 
#   The parent could have a `field type_string, type: String`
#   and a method #type that calls and memoizes `self.type_string.camelize.constantize`
#

class Parent
  def association_in_memory
    @association_in_memory ||= code_to_get_all_association
  end

  def my_child?(child)
    # ...
  end
end

class Child
  # nothing particular
end

allow_sideload :association_in_memory, resource: InMemoryResource do
  # Read the association in memory, 
  # we flatten everything in the same array
  scope do |parents|
    parents.all.flat_map(&:association_in_memory) # before they get filtered or whatever
  end

  # Now our flattened array was just filtered, we need to "reassign" what was previously assigned to the right guy
  assign do |parents, children_in_memory_after_getting_filtered_or_whatever|
    tldr = children_in_memory_after_getting_filtered_or_whatever
    parents.each do |parent|
      children_belonging_to_parent = children_in_memory_after_getting_filtered_or_whatever.select do |child|
        parent.my_child?(child)
      end
      parent.instance_variable_set('@association_in_memory', children_belonging_to_parent)
    end
  end
end