about summary refs log tree commit diff
path: root/app/models/glitch/keyword_mute.rb
diff options
context:
space:
mode:
authorDavid Yip <yipdw@member.fsf.org>2017-10-21 14:47:17 -0500
committerDavid Yip <yipdw@member.fsf.org>2017-10-21 14:54:36 -0500
commit670e6a33f8eeca628707dc020e02ce32502d74a4 (patch)
tree527043ee2b85d5a18dc5c51acd7277fc560b3e78 /app/models/glitch/keyword_mute.rb
parentcd04e3df58c09b0faca81ccc820b2cd5e12c2890 (diff)
Move KeywordMute into Glitch namespace.
There are two motivations for this:

1. It looks like we're going to add other features that require
   server-side storage (e.g. user notes).

2. Namespacing glitchsoc modifications is a good idea anyway: even if we
   do not end up doing (1), if upstream introduces a keyword-mute feature
   that also uses a "KeywordMute" model, we can avoid some merge
   conflicts this way and work on the more interesting task of
   choosing which implementation to use.
Diffstat (limited to 'app/models/glitch/keyword_mute.rb')
-rw-r--r--app/models/glitch/keyword_mute.rb49
1 files changed, 49 insertions, 0 deletions
diff --git a/app/models/glitch/keyword_mute.rb b/app/models/glitch/keyword_mute.rb
new file mode 100644
index 000000000..3b0b47f52
--- /dev/null
+++ b/app/models/glitch/keyword_mute.rb
@@ -0,0 +1,49 @@
+# frozen_string_literal: true
+# == Schema Information
+#
+# Table name: glitch_keyword_mutes
+#
+#  id         :integer          not null, primary key
+#  account_id :integer          not null
+#  keyword    :string           not null
+#  whole_word :boolean          default(TRUE), not null
+#  created_at :datetime         not null
+#  updated_at :datetime         not null
+#
+
+class Glitch::KeywordMute < ApplicationRecord
+  belongs_to :account, required: true
+
+  validates_presence_of :keyword
+
+  after_commit :invalidate_cached_matcher
+
+  def self.matcher_for(account_id)
+    Rails.cache.fetch("keyword_mutes:matcher:#{account_id}") { Matcher.new(account_id) }
+  end
+
+  private
+
+  def invalidate_cached_matcher
+    Rails.cache.delete("keyword_mutes:matcher:#{account_id}")
+  end
+
+  class Matcher
+    attr_reader :regex
+
+    def initialize(account_id)
+      re = [].tap do |arr|
+        Glitch::KeywordMute.where(account_id: account_id).select(:keyword, :id, :whole_word).find_each do |m|
+          boundary = m.whole_word ? '\b' : ''
+          arr << "#{boundary}#{Regexp.escape(m.keyword.strip)}#{boundary}"
+        end
+      end.join('|')
+
+      @regex = /#{re}/i unless re.empty?
+    end
+
+    def =~(str)
+      regex ? regex =~ str : false
+    end
+  end
+end