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.
 
 
 
 

56 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. # irreversible :boolean default(FALSE), not null
  12. # created_at :datetime not null
  13. # updated_at :datetime not null
  14. #
  15. class CustomFilter < ApplicationRecord
  16. VALID_CONTEXTS = %w(
  17. home
  18. notifications
  19. public
  20. thread
  21. ).freeze
  22. include Expireable
  23. belongs_to :account
  24. validates :phrase, :context, presence: true
  25. validate :context_must_be_valid
  26. validate :irreversible_must_be_within_context
  27. scope :active_irreversible, -> { where(irreversible: true).where(Arel.sql('expires_at IS NULL OR expires_at > NOW()')) }
  28. before_validation :clean_up_contexts
  29. after_commit :remove_cache
  30. private
  31. def clean_up_contexts
  32. self.context = Array(context).map(&:strip).map(&:presence).compact
  33. end
  34. def remove_cache
  35. Rails.cache.delete("filters:#{account_id}")
  36. Redis.current.publish("timeline:#{account_id}", Oj.dump(event: :filters_changed))
  37. end
  38. def context_must_be_valid
  39. errors.add(:context, I18n.t('filters.errors.invalid_context')) if context.empty? || context.any? { |c| !VALID_CONTEXTS.include?(c) }
  40. end
  41. def irreversible_must_be_within_context
  42. errors.add(:irreversible, I18n.t('filters.errors.invalid_irreversible')) if irreversible? && !context.include?('home') && !context.include?('notifications')
  43. end
  44. end