From f5a32839761f4951dc09ecbf207573183c6e2f80 Mon Sep 17 00:00:00 2001 From: David Yip Date: Tue, 24 Oct 2017 18:31:34 -0500 Subject: [PATCH] Switch to Regexp.union for building the mute expression. Also make the keyword-building methods private: they always probably should have been private, but now I have encoded enough fun and games into them that it now seems wrong for them to *not* be private. --- app/models/glitch/keyword_mute.rb | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/app/models/glitch/keyword_mute.rb b/app/models/glitch/keyword_mute.rb index 4c3e69de49..f0969c65e6 100644 --- a/app/models/glitch/keyword_mute.rb +++ b/app/models/glitch/keyword_mute.rb @@ -35,30 +35,32 @@ class Glitch::KeywordMute < ApplicationRecord def initialize(account_id) @account_id = account_id regex_text = Rails.cache.fetch("keyword_mutes:regex:#{account_id}") { regex_text_for_account } - @regex = /#{regex_text}/i unless regex_text.empty? + @regex = /#{regex_text}/i end + def =~(str) + regex ? regex =~ str : nil + end + + private + def keywords Glitch::KeywordMute.where(account_id: account_id).select(:keyword, :id, :whole_word) end def regex_text_for_account - [].tap do |arr| - keywords.find_each do |kw| - arr << (kw.whole_word ? boundary_regex_for_keyword(kw.keyword) : Regexp.escape(kw.keyword)) - end - end.join('|') + kws = keywords.find_each.with_object([]) do |kw, a| + a << (kw.whole_word ? boundary_regex_for_keyword(kw.keyword) : kw.keyword) + end + + Regexp.union(kws).source end def boundary_regex_for_keyword(keyword) sb = keyword =~ /\A[[:word:]]/ ? '\b' : '' eb = keyword =~ /[[:word:]]\Z/ ? '\b' : '' - "#{sb}#{Regexp.escape(keyword)}#{eb}" - end - - def =~(str) - regex ? regex =~ str : nil + /#{sb}#{Regexp.escape(keyword)}#{eb}/ end end end