From 9ddff8d3582e0200b7594c3de24e7ad50604cd65 Mon Sep 17 00:00:00 2001 From: Jared Beck Date: Tue, 13 Dec 2016 22:41:09 -0500 Subject: [PATCH] Extract private method load_versions_for_hmt_association --- .rubocop_todo.yml | 2 +- lib/paper_trail/reifier.rb | 38 +++++++++++++++++++++++--------------- 2 files changed, 24 insertions(+), 16 deletions(-) diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index 5b3e565e..cadc7cd3 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -2,7 +2,7 @@ # one by one as the offenses are removed from the code base. Metrics/AbcSize: - Max: 24 # Goal: 15 + Max: 22 # Goal: 15 Metrics/CyclomaticComplexity: Max: 8 # Goal: 6 diff --git a/lib/paper_trail/reifier.rb b/lib/paper_trail/reifier.rb index 53dc1b23..09ca5795 100644 --- a/lib/paper_trail/reifier.rb +++ b/lib/paper_trail/reifier.rb @@ -117,23 +117,12 @@ module PaperTrail end # @api private - def hmt_collection_through_belongs_to(through_collection, assoc, options, transaction_id) - collection_keys = through_collection.map { |through_model| + def hmt_collection_through_belongs_to(through_collection, assoc, options, tx_id) + ids = through_collection.map { |through_model| through_model.send(assoc.source_reflection.foreign_key) } - version_id_subquery = assoc.klass.paper_trail.version_class. - select("MIN(id)"). - where("item_type = ?", assoc.class_name). - where("item_id IN (?)", collection_keys). - where( - "created_at >= ? OR transaction_id = ?", - options[:version_at], - transaction_id - ). - group("item_id"). - to_sql - versions = versions_by_id(assoc.klass, version_id_subquery) - collection = Array.new assoc.klass.where(assoc.klass.primary_key => collection_keys) + versions = load_versions_for_hmt_association(assoc, ids, tx_id, options[:version_at]) + collection = Array.new assoc.klass.where(assoc.klass.primary_key => ids) prepare_array_for_has_many(collection, options, versions) collection end @@ -217,6 +206,25 @@ module PaperTrail versions_by_id(model.class, version_id_subquery) end + # Given a `has_many(through:)` association and an array of `ids`, return + # the version records from the point in time identified by `tx_id` or + # `version_at`. + # @api private + def load_versions_for_hmt_association(assoc, ids, tx_id, version_at) + version_id_subquery = assoc.klass.paper_trail.version_class. + select("MIN(id)"). + where("item_type = ?", assoc.class_name). + where("item_id IN (?)", ids). + where( + "created_at >= ? OR transaction_id = ?", + version_at, + tx_id + ). + group("item_id"). + to_sql + versions_by_id(assoc.klass, version_id_subquery) + end + # Set all the attributes in this version on the model. def reify_attributes(model, version, attrs) enums = model.class.respond_to?(:defined_enums) ? model.class.defined_enums : {}