The code powering m.abunchtell.com https://m.abunchtell.com
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.
 
 
 
 

57 lines
1.6 KiB

  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: custom_filters
  5. #
  6. # id :bigint(8) not null, primary key
  7. # account_id :bigint(8)
  8. # expires_at :datetime
  9. # phrase :text default(""), not null
  10. # context :string default([]), not null, is an Array
  11. # whole_word :boolean default(TRUE), not null
  12. # irreversible :boolean default(FALSE), not null
  13. # created_at :datetime not null
  14. # updated_at :datetime not null
  15. #
  16. class CustomFilter < ApplicationRecord
  17. VALID_CONTEXTS = %w(
  18. home
  19. notifications
  20. public
  21. thread
  22. ).freeze
  23. include Expireable
  24. belongs_to :account
  25. validates :phrase, :context, presence: true
  26. validate :context_must_be_valid
  27. validate :irreversible_must_be_within_context
  28. scope :active_irreversible, -> { where(irreversible: true).where(Arel.sql('expires_at IS NULL OR expires_at > NOW()')) }
  29. before_validation :clean_up_contexts
  30. after_commit :remove_cache
  31. private
  32. def clean_up_contexts
  33. self.context = Array(context).map(&:strip).map(&:presence).compact
  34. end
  35. def remove_cache
  36. Rails.cache.delete("filters:#{account_id}")
  37. Redis.current.publish("timeline:#{account_id}", Oj.dump(event: :filters_changed))
  38. end
  39. def context_must_be_valid
  40. errors.add(:context, I18n.t('filters.errors.invalid_context')) if context.empty? || context.any? { |c| !VALID_CONTEXTS.include?(c) }
  41. end
  42. def irreversible_must_be_within_context
  43. errors.add(:irreversible, I18n.t('filters.errors.invalid_irreversible')) if irreversible? && !context.include?('home') && !context.include?('notifications')
  44. end
  45. end