FIX: Allow regular expressions to specify boundaries

This commit is contained in:
Robin Ward 2017-11-17 14:10:38 -05:00
parent de037da731
commit d755c9c90f
2 changed files with 40 additions and 16 deletions

View File

@ -15,14 +15,22 @@ class WordWatcher
def self.word_matcher_regexp(action) def self.word_matcher_regexp(action)
s = Discourse.cache.fetch(word_matcher_regexp_key(action), expires_in: 1.day) do s = Discourse.cache.fetch(word_matcher_regexp_key(action), expires_in: 1.day) do
words = words_for_action(action) words = words_for_action(action)
words.empty? ? nil : '\b(' + words.map { |w| word_to_regexp(w) }.join('|'.freeze) + ')\b' if words.empty?
nil
else
regexp = '(' + words.map { |w| word_to_regexp(w) }.join('|'.freeze) + ')'
SiteSetting.watched_words_regular_expressions? ? regexp : "(#{regexp})"
end
end end
s.present? ? Regexp.new(s, Regexp::IGNORECASE) : nil s.present? ? Regexp.new(s, Regexp::IGNORECASE) : nil
end end
def self.word_to_regexp(word) def self.word_to_regexp(word)
return word if SiteSetting.watched_words_regular_expressions? if SiteSetting.watched_words_regular_expressions?
# Strip ruby regexp format if present, we're going to make the whole thing
# case insensitive anyway
return word.start_with?("(?-mix:") ? word[7..-2] : word
end
Regexp.escape(word).gsub("\\*", '\S*') Regexp.escape(word).gsub("\\*", '\S*')
end end

View File

@ -48,20 +48,36 @@ describe WordWatcher do
expect(m[1]).to eq("acknowledge") expect(m[1]).to eq("acknowledge")
end end
it "supports regular expressions as a site setting" do context "regular expressions" do
SiteSetting.watched_words_regular_expressions = true before do
Fabricate( SiteSetting.watched_words_regular_expressions = true
:watched_word, end
word: "tro[uo]+t",
action: WatchedWord.actions[:require_approval] it "supports regular expressions on word boundaries" do
) Fabricate(
m = WordWatcher.new("Evil Trout is cool").word_matches_for_action?(:require_approval) :watched_word,
expect(m[1]).to eq("Trout") word: /\btest\b/,
m = WordWatcher.new("Evil Troot is cool").word_matches_for_action?(:require_approval) action: WatchedWord.actions[:block]
expect(m[1]).to eq("Troot") )
m = WordWatcher.new("trooooooooot").word_matches_for_action?(:require_approval) m = WordWatcher.new("this is not a test.").word_matches_for_action?(:block)
expect(m[1]).to eq("trooooooooot") expect(m[1]).to eq("test")
end
it "supports regular expressions as a site setting" do
Fabricate(
:watched_word,
word: /tro[uo]+t/,
action: WatchedWord.actions[:require_approval]
)
m = WordWatcher.new("Evil Trout is cool").word_matches_for_action?(:require_approval)
expect(m[1]).to eq("Trout")
m = WordWatcher.new("Evil Troot is cool").word_matches_for_action?(:require_approval)
expect(m[1]).to eq("Troot")
m = WordWatcher.new("trooooooooot").word_matches_for_action?(:require_approval)
expect(m[1]).to eq("trooooooooot")
end
end end
end end
end end