Skip to content

Commit

Permalink
Correctly recurse over nested field associations
Browse files Browse the repository at this point in the history
  • Loading branch information
d-m-u committed Jun 18, 2019
1 parent 921ae9f commit 2ece9be
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 8 deletions.
16 changes: 10 additions & 6 deletions app/models/dialog_field_association_validator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,19 @@ def circular_references(associations)
private

def initial_paths(associations)
associations.flat_map { |key, values| values.map { |value| [key, value] } }
associations.flat_map { |key, values| values.map { |value| [key, value] if associations.key?(value) } }.compact
end

def walk_value_path(fieldname_being_triggered, associations, path)
while associations[fieldname_being_triggered].present?
return [fieldname_being_triggered, associations[fieldname_being_triggered].first] if path.include?(associations[fieldname_being_triggered].first)
path << associations[fieldname_being_triggered]
path.flatten!
fieldname_being_triggered = path.last
while associations[fieldname_being_triggered]
return [fieldname_being_triggered, (path & associations[fieldname_being_triggered]).first] if (path & associations[fieldname_being_triggered]).present?

associations[fieldname_being_triggered].map do |new_element|
path_copy = path.dup
path_copy << new_element
fieldname_being_triggered = new_element
walk_value_path(fieldname_being_triggered, associations, path_copy)
end
end
end
end
7 changes: 5 additions & 2 deletions spec/models/dialog_field_association_validator_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,12 @@

context "when the associations are not blank" do
context "when there are no circular references" do
it "returns false" do
it "returns false on the trivial case" do
expect(dialog_field_association_validator.circular_references("foo" => ["baz"])).to eq(false)
expect(dialog_field_association_validator.circular_references("foo" => %w(foo2 foo4), "foo2" => ["foo3"], "foo3" => ["foo4"])).to eq(false)
end

it "returns false on the non-trivial case" do
expect(dialog_field_association_validator.circular_references("e" => ["c"], "c" => ["a", "d"], "d" => ["a"])).to eq(false)
end
end

Expand Down

0 comments on commit 2ece9be

Please sign in to comment.