diff --git a/app/models/notification.rb b/app/models/notification.rb index eb4932a3bf31..617a7e99b907 100644 --- a/app/models/notification.rb +++ b/app/models/notification.rb @@ -13,6 +13,8 @@ class Notification < ApplicationRecord # Do not emit notifications if they are not enabled for the server after_commit :emit_message, :on => :create + before_save :backup_subject_name + serialize :options, Hash default_value_for(:options) { Hash.new } @@ -40,6 +42,12 @@ def to_h } end + def backup_subject_name + return unless subject + backup_name = (subject.try(:name) || subject.try(:description)) + self.options[:subject] = backup_name if backup_name + end + def seen_by_all_recipients? notification_recipients.unseen.empty? end diff --git a/spec/models/notification_spec.rb b/spec/models/notification_spec.rb index 83ee0d12a620..c89542586e4e 100644 --- a/spec/models/notification_spec.rb +++ b/spec/models/notification_spec.rb @@ -112,6 +112,44 @@ ) ) end + + context "subject text" do + let(:vm) { FactoryGirl.create(:vm, :tenant => tenant) } + subject { Notification.create(:type => :vm_snapshot_failure, :subject => vm, :options => {:error => "oops", :snapshot_op => "create"}) } + + it "stuffs subject into options hash in case the subject is destroyed" do + expect(subject.options[:subject]).to eql(subject.subject.name) + end + + it "detects a rename of the subject" do + subject + vm_name = "#{vm.name}_1" + vm.update(:name => vm_name) + + note = Notification.first + expect(note.to_h.fetch_path(:bindings, :subject, :text)).to eql(vm_name) + end + + it "retains name incase subject is destroyed" do + subject + vm_name = vm.name + vm.destroy + + note = Notification.first + expect(note.to_h.fetch_path(:bindings, :subject, :text)).to eql(vm_name) + end + + it "doesn't detect subject rename if subject is destroyed" do + subject + original_name = vm.name + vm_name = "#{vm.name}_1" + vm.update(:name => vm_name) + vm.destroy + + note = Notification.first + expect(note.to_h.fetch_path(:bindings, :subject, :text)).to eql(original_name) + end + end end describe "#seen_by_all_recipients?" do