Don't error when category doesn't have a custom field (#26)

Don’t error when category doesn’t have a custom field (#26)

diff --git a/app/controllers/category_experts_controller.rb b/app/controllers/category_experts_controller.rb
index d0440f2..6de3102 100644
--- a/app/controllers/category_experts_controller.rb
+++ b/app/controllers/category_experts_controller.rb
@@ -56,8 +56,8 @@ class CategoryExpertsController < ApplicationController
     category = post.topic.category
     return false unless category
 
-    expert_group_ids = category.custom_fields[CategoryExperts::CATEGORY_EXPERT_GROUP_IDS].split("|").map(&:to_i)
-    return false if expert_group_ids.count == 0
+    expert_group_ids = category.custom_fields[CategoryExperts::CATEGORY_EXPERT_GROUP_IDS]&.split("|")&.map(&:to_i)
+    return false if expert_group_ids.nil? || expert_group_ids.count == 0
 
     (expert_group_ids & (post.user.group_ids || [])).count > 0
   end
diff --git a/spec/requests/category_experts_controller_spec.rb b/spec/requests/category_experts_controller_spec.rb
index b62553a..fbcf598 100644
--- a/spec/requests/category_experts_controller_spec.rb
+++ b/spec/requests/category_experts_controller_spec.rb
@@ -209,6 +209,18 @@ describe CategoryExpertsController do
         sign_in(admin)
       end
 
+      it "return false when the category has no category expert groups" do
+        post = create_post(topic_id: topic.id, user: random_user)
+        CategoryCustomField.find_by(
+          category_id: post.topic.category.id,
+          name: CategoryExperts::CATEGORY_EXPERT_GROUP_IDS
+        ).destroy
+        get "/category-experts/retroactive-approval/#{post.id}.json"
+
+        expect(response.status).to eq(200)
+        expect(response.parsed_body["can_be_approved"]).to eq(false)
+      end
+
       it "return false when the post is not by a category expert" do
         post = create_post(topic_id: topic.id, user: random_user)
         get "/category-experts/retroactive-approval/#{post.id}.json"

GitHub sha: 8e55e917

This commit appears in #26 which was approved by Falco. It was merged by markvanlan.