You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
50 lines
1.2 KiB
50 lines
1.2 KiB
7 years ago
|
# frozen_string_literal: true
|
||
7 years ago
|
# == Schema Information
|
||
|
#
|
||
7 years ago
|
# Table name: glitch_keyword_mutes
|
||
7 years ago
|
#
|
||
|
# id :integer not null, primary key
|
||
|
# account_id :integer not null
|
||
|
# keyword :string not null
|
||
7 years ago
|
# whole_word :boolean default(TRUE), not null
|
||
7 years ago
|
# created_at :datetime not null
|
||
|
# updated_at :datetime not null
|
||
|
#
|
||
|
|
||
7 years ago
|
class Glitch::KeywordMute < ApplicationRecord
|
||
7 years ago
|
belongs_to :account, required: true
|
||
|
|
||
|
validates_presence_of :keyword
|
||
|
|
||
7 years ago
|
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}")
|
||
7 years ago
|
end
|
||
|
|
||
|
class Matcher
|
||
|
attr_reader :regex
|
||
|
|
||
7 years ago
|
def initialize(account_id)
|
||
7 years ago
|
re = [].tap do |arr|
|
||
7 years ago
|
Glitch::KeywordMute.where(account_id: account_id).select(:keyword, :id, :whole_word).find_each do |m|
|
||
7 years ago
|
boundary = m.whole_word ? '\b' : ''
|
||
|
arr << "#{boundary}#{Regexp.escape(m.keyword.strip)}#{boundary}"
|
||
7 years ago
|
end
|
||
7 years ago
|
end.join('|')
|
||
7 years ago
|
|
||
7 years ago
|
@regex = /#{re}/i unless re.empty?
|
||
7 years ago
|
end
|
||
|
|
||
|
def =~(str)
|
||
7 years ago
|
regex ? regex =~ str : false
|
||
7 years ago
|
end
|
||
7 years ago
|
end
|
||
7 years ago
|
end
|