DEV: Avoid nil custom fields (#154)

DEV: Avoid nil custom fields (#154)

Included:

  • DEV: Topic#custom_fields is always truthy
  • DEV: Delete custom fields instead of setting nil
  • DEV: Delete existing nil custom fields
diff --git a/db/post_migrate/20210429154319_remove_nil_custom_fields_from_assign.rb b/db/post_migrate/20210429154319_remove_nil_custom_fields_from_assign.rb
new file mode 100644
index 0000000..a9c187a
--- /dev/null
+++ b/db/post_migrate/20210429154319_remove_nil_custom_fields_from_assign.rb
@@ -0,0 +1,19 @@
+# frozen_string_literal: true
+
+class RemoveNilCustomFieldsFromAssign < ActiveRecord::Migration[6.0]
+  def up
+    execute <<~SQL
+      DELETE FROM topic_custom_fields
+      WHERE name = 'assigned_to_id' AND value IS NULL
+    SQL
+
+    execute <<~SQL
+      DELETE FROM topic_custom_fields
+      WHERE name = 'assigned_by_id' AND value IS NULL
+    SQL
+  end
+
+  def down
+    raise ActiveRecord::IrreversibleMigration
+  end
+end
diff --git a/lib/topic_assigner.rb b/lib/topic_assigner.rb
index 6d9fb05..13d59bb 100644
--- a/lib/topic_assigner.rb
+++ b/lib/topic_assigner.rb
@@ -148,7 +148,7 @@ class ::TopicAssigner
       return { success: false, reason: reason }
     end
     return { success: false, reason: :forbidden_assign_to } unless can_be_assigned?(assign_to)
-    return { success: false, reason: :already_assigned } if @topic.custom_fields && @topic.custom_fields[ASSIGNED_TO_ID] == assign_to.id.to_s
+    return { success: false, reason: :already_assigned } if @topic.custom_fields[ASSIGNED_TO_ID] == assign_to.id.to_s
     return { success: false, reason: :too_many_assigns } unless can_assign_to?(assign_to)
 
     @topic.custom_fields[ASSIGNED_TO_ID] = assign_to.id
@@ -279,8 +279,8 @@ class ::TopicAssigner
       end
 
       # clean up in memory object
-      @topic.custom_fields[ASSIGNED_TO_ID] = nil
-      @topic.custom_fields[ASSIGNED_BY_ID] = nil
+      @topic.custom_fields.delete(ASSIGNED_TO_ID)
+      @topic.custom_fields.delete(ASSIGNED_BY_ID)
 
       # nothing to do here
       return if !assigned_to_id

GitHub sha: 573c6080

This commit appears in #154 which was approved by eviltrout. It was merged by CvX.