From a9b3a9c6738fbcf7eb2a7b35c644d88c44880861 Mon Sep 17 00:00:00 2001 From: Lauryn Menard Date: Mon, 20 Mar 2023 19:58:10 +0100 Subject: [PATCH] narrow: Use dict to map operator to by_* method in NarrowBuilder. Updates the logic for identifying the method to use to extend the query for the given term from a narrow to use a dictionary that maps the operator string to the by_* method in the NarrowBuilder class. Previously, the by_* method was determined by building a string based on the operator string and replacing dashes with underscores. --- zerver/lib/narrow.py | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/zerver/lib/narrow.py b/zerver/lib/narrow.py index e5c419c9fa..3d2ffd963a 100644 --- a/zerver/lib/narrow.py +++ b/zerver/lib/narrow.py @@ -256,6 +256,20 @@ class NarrowBuilder: self.msg_id_column = msg_id_column self.realm = realm self.is_web_public_query = is_web_public_query + self.by_method_map = { + "has": self.by_has, + "in": self.by_in, + "is": self.by_is, + "stream": self.by_stream, + "streams": self.by_streams, + "topic": self.by_topic, + "sender": self.by_sender, + "near": self.by_near, + "id": self.by_id, + "search": self.by_search, + "pm-with": self.by_pm_with, + "group-pm-with": self.by_group_pm_with, + } def add_term(self, query: Select, term: Dict[str, Any]) -> Select: """ @@ -278,9 +292,9 @@ class NarrowBuilder: negated = term.get("negated", False) - method_name = "by_" + operator.replace("-", "_") - method = getattr(self, method_name, None) - if method is None: + if operator in self.by_method_map: + method = self.by_method_map[operator] + else: raise BadNarrowOperatorError("unknown operator " + operator) if negated: