1
0
Fork 0
mirror of https://github.com/paper-trail-gem/paper_trail.git synced 2022-11-09 11:33:19 -05:00

Extract private method load_versions_for_hmt_association

This commit is contained in:
Jared Beck 2016-12-13 22:41:09 -05:00
parent 14eee417a7
commit 9ddff8d358
2 changed files with 24 additions and 16 deletions

View file

@ -2,7 +2,7 @@
# one by one as the offenses are removed from the code base. # one by one as the offenses are removed from the code base.
Metrics/AbcSize: Metrics/AbcSize:
Max: 24 # Goal: 15 Max: 22 # Goal: 15
Metrics/CyclomaticComplexity: Metrics/CyclomaticComplexity:
Max: 8 # Goal: 6 Max: 8 # Goal: 6

View file

@ -117,23 +117,12 @@ module PaperTrail
end end
# @api private # @api private
def hmt_collection_through_belongs_to(through_collection, assoc, options, transaction_id) def hmt_collection_through_belongs_to(through_collection, assoc, options, tx_id)
collection_keys = through_collection.map { |through_model| ids = through_collection.map { |through_model|
through_model.send(assoc.source_reflection.foreign_key) through_model.send(assoc.source_reflection.foreign_key)
} }
version_id_subquery = assoc.klass.paper_trail.version_class. versions = load_versions_for_hmt_association(assoc, ids, tx_id, options[:version_at])
select("MIN(id)"). collection = Array.new assoc.klass.where(assoc.klass.primary_key => ids)
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)
prepare_array_for_has_many(collection, options, versions) prepare_array_for_has_many(collection, options, versions)
collection collection
end end
@ -217,6 +206,25 @@ module PaperTrail
versions_by_id(model.class, version_id_subquery) versions_by_id(model.class, version_id_subquery)
end 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. # Set all the attributes in this version on the model.
def reify_attributes(model, version, attrs) def reify_attributes(model, version, attrs)
enums = model.class.respond_to?(:defined_enums) ? model.class.defined_enums : {} enums = model.class.respond_to?(:defined_enums) ? model.class.defined_enums : {}