about summary refs log tree commit diff
path: root/db/migrate/20180707193142_migrate_filters.rb
blob: 067c5335798cebab1bdb686152c62baf92aa4a89 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class MigrateFilters < ActiveRecord::Migration[5.2]
  class GlitchKeywordMute < ApplicationRecord
    # Dummy class, as we removed Glitch::KeywordMute
    belongs_to :account, required: true
    validates_presence_of :keyword
  end

  class CustomFilter < ApplicationRecord
    # Dummy class, in case CustomFilter gets altered in the future
    belongs_to :account
    validates :phrase, :context, presence: true

    before_validation :clean_up_contexts

    private

    def clean_up_contexts
      self.context = Array(context).map(&:strip).map(&:presence).compact
    end
  end

  disable_ddl_transaction!

  def up
    GlitchKeywordMute.find_each do |filter|
      filter.account.custom_filters.create!(
        phrase: filter.keyword,
        context: filter.apply_to_mentions ? %w(home public notifications) : %w(home public),
        whole_word: filter.whole_word,
        irreversible: true)
    end
  end

  def down
    unless table_exists? :glitch_keyword_mutes
      create_table :glitch_keyword_mutes do |t|
        t.references :account, null: false
        t.string :keyword, null: false
        t.boolean :whole_word, default: true, null: false
        t.boolean :apply_to_mentions, default: true, null: false
        t.timestamps
      end

      safety_assured { add_foreign_key :glitch_keyword_mutes, :accounts, on_delete: :cascade }
    end

    CustomFilter.where(irreversible: true).find_each do |filter|
      GlitchKeywordMute.where(account: filter.account).create!(
        keyword: filter.phrase,
        whole_word: filter.whole_word,
        apply_to_mentions: filter.context.include?('notifications'))
    end
  end
end