ruby 用于合并现有话语用户的脚本

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby 用于合并现有话语用户的脚本相关的知识,希望对你有一定的参考价值。

module DiscourseUsersMerger

  class Merger
    def merge(target_username, source_username)
      raise "User to merge and target user can't be the same" if target_username == source_username
      target_user = User.find_by_username!(target_username)
      source_user = User.find_by_username!(source_username)
      puts "About to merge #{source_username} (#{source_user.email}) into #{target_username} (#{target_user.email})"
      puts "#{source_user.topics.count} topics with #{source_user.posts.count} posts will be moved. Ok to continue? (y/n)"
      continue = STDIN.gets.chomp.downcase == 'y'
      perform_merge(target_user, source_user) if continue
    end

    private

    def perform_merge(target_user, source_user)
      puts "Merging..."
      source_user.posts.update_all user_id: target_user.id
      source_user.topics.update_all user_id: target_user.id
      source_user.user_actions.each { |ua| ua.update_column(:user_id, target_user.id) rescue puts "error #{ua.inspect}" }
      puts "Deleting #{source_user.email}..."
      source_user.reload.destroy
      puts "Updating topics statistics"
      target_user.topics.each { |topic| topic.update_statistics }
      target_user.user_stat.update_topic_reply_count

      create_user_actions(target_user)
    end

    def create_user_actions(target_user)
      target_user.user_actions.where("action_type in (?)", [4, 5]).destroy_all

      UserAction.record_timestamps = false
      target_user.topics.each { |topic| create_user_action_for_topic(target_user, topic) }
      target_user.posts.each { |post| create_user_action_for_post(post, target_user) }
    end

    def create_user_action_for_post(post, target_user)
      UserAction.create!(user_id: target_user.id, target_topic_id: post.topic.id, target_post_id: post.id, action_type: 5,
                         created_at: post.created_at, updated_at: post.updated_at, acting_user_id: target_user.id) rescue puts "Error"
    end

    def create_user_action_for_topic(target_user, topic)
      UserAction.create!(user_id: target_user.id, target_topic_id: topic.id, target_post_id: -1, action_type: 4,
                         created_at: topic.created_at, updated_at: topic.updated_at, acting_user_id: target_user.id) rescue puts "Error"
    end
  end
end

raise "Usage: 'discourse_users_merger <target_username> <source_username>'" unless ARGV.length==2
DiscourseUsersMerger::Merger.new.merge(ARGV[0], ARGV[1])

以上是关于ruby 用于合并现有话语用户的脚本的主要内容,如果未能解决你的问题,请参考以下文章

ruby 用于从现有Vagrant框实例打包VMware Vagrant框的脚本

ruby 用于列出已合并到指定分支的所有远程分支的脚本。 (可选)使用最近提交排除分支。书面

ruby 用于从Facebook用户数据转储收集电话记录统计信息的Ruby脚本

ruby 用于清理Bifrost DB中的无效用户和客户端的脚本

使用用户指定的脚本重新启动现有 Amazon EC2 实例?

ruby 用于检查Codeship状态的简单Ruby脚本