Sha256: aa95d3fe2b891a470c77fd7fbe05224eb1ad460ca7c70913c4b14a24827878d0

Contents?: true

Size: 1.66 KB

Versions: 2

Compression:

Stored size: 1.66 KB

Contents

# frozen_string_literal: true
module Thredded
  class MessageboardDestroyer
    def initialize(messageboard_name)
      @messageboard = Thredded::Messageboard.friendly.find(messageboard_name)
      @connection = ActiveRecord::Base.connection
    rescue
      say "No messageboard with the name '#{messageboard_name}' found."
    end

    def run
      return unless messageboard

      ActiveRecord::Base.transaction do
        destroy_all_lower_dependencies
        destroy_all_posts
        destroy_all_topics
        destroy_messageboard_and_everything_else
      end
    end

    private

    attr_reader :messageboard, :connection

    def destroy_all_lower_dependencies
      say 'Destroying lower level dependencies ...'
      [PostNotification.joins(non_private_post: :postable), UserTopicReadState.joins(:postable)].each do |child_t|
        child_t.merge(Topic.where(messageboard_id: messageboard.id)).delete_all
      end

      Thredded::MessageboardUser
        .where(thredded_messageboard_id: messageboard.id)
        .delete_all
    end

    def destroy_all_posts
      say 'Destroying all posts ...'

      connection.execute <<-SQL
        DELETE FROM thredded_posts
          WHERE messageboard_id = #{messageboard.id}
      SQL
    end

    def destroy_all_topics
      say 'Destroying all topics ...'

      connection.execute <<-SQL
        DELETE FROM thredded_topics
          WHERE messageboard_id = #{messageboard.id}
      SQL
    end

    def destroy_messageboard_and_everything_else
      say 'Destroying messageboard and everything else. Sit tight ...'

      @messageboard.destroy!
    end

    def say(message)
      puts message unless Rails.env.test?
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
thredded-0.3.1 app/commands/thredded/messageboard_destroyer.rb
thredded-0.3.0 app/commands/thredded/messageboard_destroyer.rb