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.
This commit is contained in:
David Yip 2017-10-24 18:31:34 -05:00
parent 8410d33b49
commit f5a3283976

View file

@ -35,30 +35,32 @@ class Glitch::KeywordMute < ApplicationRecord
def initialize(account_id) def initialize(account_id)
@account_id = account_id @account_id = account_id
regex_text = Rails.cache.fetch("keyword_mutes:regex:#{account_id}") { regex_text_for_account } 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 end
def =~(str)
regex ? regex =~ str : nil
end
private
def keywords def keywords
Glitch::KeywordMute.where(account_id: account_id).select(:keyword, :id, :whole_word) Glitch::KeywordMute.where(account_id: account_id).select(:keyword, :id, :whole_word)
end end
def regex_text_for_account def regex_text_for_account
[].tap do |arr| kws = keywords.find_each.with_object([]) do |kw, a|
keywords.find_each do |kw| a << (kw.whole_word ? boundary_regex_for_keyword(kw.keyword) : kw.keyword)
arr << (kw.whole_word ? boundary_regex_for_keyword(kw.keyword) : Regexp.escape(kw.keyword)) end
end
end.join('|') Regexp.union(kws).source
end end
def boundary_regex_for_keyword(keyword) def boundary_regex_for_keyword(keyword)
sb = keyword =~ /\A[[:word:]]/ ? '\b' : '' sb = keyword =~ /\A[[:word:]]/ ? '\b' : ''
eb = keyword =~ /[[:word:]]\Z/ ? '\b' : '' eb = keyword =~ /[[:word:]]\Z/ ? '\b' : ''
"#{sb}#{Regexp.escape(keyword)}#{eb}" /#{sb}#{Regexp.escape(keyword)}#{eb}/
end
def =~(str)
regex ? regex =~ str : nil
end end
end end
end end