Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@janpaul123
Created September 29, 2017 06:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save janpaul123/c959e998663949524525d4fcac1d90a3 to your computer and use it in GitHub Desktop.
Save janpaul123/c959e998663949524525d4fcac1d90a3 to your computer and use it in GitHub Desktop.
Fun recursive function to test if things like copying deep data structures work correctly. Done with @boconnell at @remix.
def identity_of_model(model, global_excluded=['id', 'created_at', 'updated_at', 'deleted_at'])
excluded_columns = model.class.reflect_on_all_associations.map(&:foreign_key) + global_excluded
identity = model.attributes.except(*excluded_columns)
model.class.reflect_on_all_associations(:has_many).sort_by(&:name).each do |ref|
identity[ref.name.to_s] = model.send(ref.name).map(&method(:identity_of_model)).sort_by(&:to_json)
end
model.class.reflect_on_all_associations(:has_and_belongs_to_many).sort_by(&:name).each do |ref|
identity["#{ref.name}_counts"] = model.send(ref.name).count
end
identity
end
identity_of_model(Map.first) == identity_of_model(copy(Map.first))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment