Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for tracking has_and_belongs_to_many associations. #217

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 28 additions & 10 deletions .rubocop_todo.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# This configuration was generated by
# `rubocop --auto-gen-config`
# on 2018-01-16 15:37:33 -0500 using RuboCop version 0.48.1.
# on 2018-01-17 21:53:45 -0500 using RuboCop version 0.48.1.
# The point is for the user to remove these configuration records
# one by one as the offenses are removed from the code base.
# Note that changes in the inspected code, or installation of new
Expand Down Expand Up @@ -31,9 +31,9 @@ Lint/ParenthesesAsGroupedExpression:
Exclude:
- 'spec/integration/integration_spec.rb'

# Offense count: 21
# Offense count: 22
Metrics/AbcSize:
Max: 45
Max: 69

# Offense count: 114
# Configuration parameters: CountComments, ExcludedMethods.
Expand All @@ -43,29 +43,29 @@ Metrics/BlockLength:
# Offense count: 1
# Configuration parameters: CountComments.
Metrics/ClassLength:
Max: 114
Max: 124

# Offense count: 5
# Offense count: 6
Metrics/CyclomaticComplexity:
Max: 10

# Offense count: 457
# Offense count: 462
# Configuration parameters: AllowHeredoc, AllowURI, URISchemes, IgnoreCopDirectives, IgnoredPatterns.
# URISchemes: http, https
Metrics/LineLength:
Max: 688

# Offense count: 15
# Offense count: 16
# Configuration parameters: CountComments.
Metrics/MethodLength:
Max: 23
Max: 26

# Offense count: 2
# Configuration parameters: CountComments.
Metrics/ModuleLength:
Max: 180
Max: 200

# Offense count: 5
# Offense count: 6
Metrics/PerceivedComplexity:
Max: 12

Expand Down Expand Up @@ -107,3 +107,21 @@ Style/IfInsideElse:
Style/MultilineBlockChain:
Exclude:
- 'lib/mongoid/history/tracker.rb'

# Offense count: 1
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles.
# SupportedStyles: symmetrical, new_line, same_line
Style/MultilineMethodCallBraceLayout:
Exclude:
- 'spec/unit/options_spec.rb'

# Offense count: 2
# Configuration parameters: NamePrefix, NamePrefixBlacklist, NameWhitelist.
# NamePrefix: is_, has_, have_
# NamePrefixBlacklist: is_, has_, have_
# NameWhitelist: is_a?
Style/PredicateName:
Exclude:
- 'spec/**/*'
- 'lib/mongoid/history/trackable.rb'
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
### 0.8.1 (Next)

* [#217](https://github.com/mongoid/mongoid-history/pull/217): Support for tracking `has_and_belongs_to_many` associations - [@dblock](https://github.com/dblock).
* Your contribution here.

### 0.8.0 (2018/01/16)
Expand Down
9 changes: 6 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -168,11 +168,11 @@ class Post
field :body
field :rating

track_history :on => [:fields] # all fields will be tracked
track_history :on => [ :fields ] # only fields will be tracked
end
```

You can also track changes on all embedded relations.
You can also track changes on all embedded (`embeds_one` and `embeds_many`) or referenced (`has_and_belongs_to_many`) relations.

```ruby
class Post
Expand All @@ -182,7 +182,10 @@ class Post
embeds_many :comments
embeds_one :content

track_history :on => [:embedded_relations] # all embedded relations will be tracked
track_history :on => [
:embedded_relations,
:referenced_relations
] # only embedded and references relations will be tracked
end
```

Expand Down
22 changes: 17 additions & 5 deletions lib/mongoid/history/attributes/create.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,16 @@ module Attributes
class Create < ::Mongoid::History::Attributes::Base
def attributes
@attributes = {}
insert_attributes
insert_embeds_one_changes
insert_embeds_many_changes
insert_has_or_belongs_to_many_changes
@attributes
end

private

def insert_attributes
trackable.attributes.each do |k, v|
next unless trackable_class.tracked_field?(k, :create)
modified = if changes[k]
Expand All @@ -13,13 +23,8 @@ def attributes
end
@attributes[k] = [nil, format_field(k, modified)]
end
insert_embeds_one_changes
insert_embeds_many_changes
@attributes
end

private

def insert_embeds_one_changes
trackable_class.tracked_embeds_one.each do |rel|
rel_class = trackable_class.relation_class_of(rel)
Expand All @@ -44,6 +49,13 @@ def insert_embeds_many_changes
.map { |obj| format_embeds_many_relation(rel, obj.attributes) }]
end
end

def insert_has_or_belongs_to_many_changes
trackable_class.referenced_relations.values.each do |rel|
k = rel.key
@attributes[k] = [nil, format_field(k, trackable.send(k))]
end
end
end
end
end
Expand Down
14 changes: 12 additions & 2 deletions lib/mongoid/history/options.rb
Original file line number Diff line number Diff line change
Expand Up @@ -82,17 +82,25 @@ def parse_tracked_fields_and_relations

if options[:on].include?(:fields)
@options[:on] = options[:on].reject { |opt| opt == :fields }
@options[:on] = options[:on] | trackable.fields.keys.map(&:to_sym) - reserved_fields.map(&:to_sym)
@options[:on] = options[:on] |
trackable.fields.keys.map(&:to_sym) -
reserved_fields.map(&:to_sym) -
trackable.referenced_relations.values.map { |r| r.key.to_sym }
end

if options[:on].include?(:embedded_relations)
@options[:on] = options[:on].reject { |opt| opt == :embedded_relations }
@options[:on] = options[:on] | trackable.embedded_relations.keys
end

if options[:on].include?(:referenced_relations)
@options[:on] = options[:on].reject { |opt| opt == :referenced_relations }
@options[:on] = options[:on] | trackable.referenced_relations.keys
end

@options[:fields] = []
@options[:dynamic] = []
@options[:relations] = { embeds_one: {}, embeds_many: {} }
@options[:relations] = { embeds_one: {}, embeds_many: {}, has_and_belongs_to_many: {} }

options[:on].each do |option|
field = get_database_field_name(option)
Expand Down Expand Up @@ -146,6 +154,8 @@ def categorize_tracked_option(field, field_options = nil)
track_relation(field, :embeds_one, field_options)
elsif trackable.embeds_many?(field)
track_relation(field, :embeds_many, field_options)
elsif trackable.has_and_belongs_to_many?(field)
track_relation(field, :has_and_belongs_to_many, field_options)
elsif trackable.fields.keys.include?(field)
@options[:fields] << field
else
Expand Down
50 changes: 50 additions & 0 deletions lib/mongoid/history/trackable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,13 @@ module Trackable
extend ActiveSupport::Concern

module ClassMethods
def has_and_belongs_to_many(field, opts = {})
super field, {
before_add: :track_references,
before_remove: :track_references
}.merge(opts)
end
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Interesting idea! Does feel like a bit of a hack though...


def track_history(options = {})
extend RelationMethods

Expand Down Expand Up @@ -248,6 +255,34 @@ def track_destroy(&block)
track_history_for_action(:destroy, &block) unless destroyed?
end

def track_references(related)
# skip for new records (track_create will capture assignment) and when track updates disabled
return true if new_record? || !track_history? || !history_trackable_options[:track_update]
metadata = reflect_on_all_associations(:has_and_belongs_to_many).find { |m| m.class_name == related.class.name }

related_id = related.id
original_ids = send(metadata.key.to_sym)
modified_ids = if original_ids.include?(related_id)
original_ids.reject { |id| id == related_id }
else
original_ids + [related_id]
end

modified = { metadata.key => modified_ids }
original = { metadata.key => original_ids }
action = :update
current_version = increment_current_version
self.class.tracker_class.create!(
history_tracker_attributes(action.to_sym).merge(
version: current_version,
action: action.to_s,
original: original,
modified: modified,
trackable: self
)
)
end

def clear_trackable_memoization
@history_tracker_attributes = nil
@modified_attributes_for_create = nil
Expand Down Expand Up @@ -328,6 +363,15 @@ def embeds_many?(field)
relation_of(field) == Mongoid::Relations::Embedded::Many
end

# Indicates whether there is an Referenced::ManyToMany relation for the given embedded field.
#
# @param [ String | Symbol ] field The name of the referenced field.
#
# @return [ Boolean ] true if there is an Referenced::ManyToMany relation for the given referenced field.
def has_and_belongs_to_many?(field)
relation_of(field) == Mongoid::Relations::Referenced::ManyToMany
end

# Retrieves the database representation of an embedded field name, in case the :store_as option is used.
#
# @param [ String | Symbol ] embed The name or alias of the embedded field.
Expand Down Expand Up @@ -438,6 +482,12 @@ def reserved_tracked_fields
end
end

def referenced_relations
relations.select do |_, r|
r.relation == Mongoid::Relations::Referenced::ManyToMany
end
end

def field_formats
@field_formats ||= history_trackable_options[:format]
end
Expand Down
Loading