Skip to content

Instantly share code, notes, and snippets.

@Startouf
Created October 25, 2018 22:13
Show Gist options
  • Save Startouf/6e95f03da2716bdcff4d7485783ca03f to your computer and use it in GitHub Desktop.
Save Startouf/6e95f03da2716bdcff4d7485783ca03f to your computer and use it in GitHub Desktop.
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment