ruby skills_wizard.rb

Posted

tags:

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

class SkillsWizard
  extend ActiveModel::Naming
  extend ActiveModel::Translation

  attr_reader :errors
  attr_reader :skill, :docs_ids

  def initialize(person)
    @person   = person
    @errors   = {}
    @skill    = nil
    @docs_ids = []
  end

  def update_skill(s_params)
    create_or_update_skill(s_params)
    destroy_unused_files
  end

  private

  def create_or_update_skill(s_params)
    docs = s_params.delete(:documentations)

    InterpreterSkill.find_by_id_or_create(s_params[:id]) do |skill|
      s_params = price_params(s_params) if skill.approved?
      skill.update(s_params)
      @skill = skill
      @errors.merge!(skill.errors_hash) && break if skill.errors.any?

      destroy_unused_docs(docs, skill)
      break unless docs.present?
      update_docs(docs, skill)
    end
  end

  def update_docs(docs, skill)
    docs.each do |doc|
      doc_files = doc.delete(:documentation_files)

      skill.documentations.find_by_id_or_create(doc[:id]) do |documentation|
        documentation.update(doc)
        @errors.merge!(documentation.errors_hash)

        next unless doc_files.present?
        update_files(doc_files, documentation)
      end
    end
  end

  def update_files(params, documentation)
    params.each do |doc_file|
      begin
        uploaded_file = DocumentationFile.find(doc_file)
        uploaded_file.update(documentation_id: documentation.id)
      rescue
        next
      end
    end
    @docs_ids = @skill.documentations.map do |d|
      [d.id, d.documentation_files.last.try(:id)]
    end
  end

  def redundant_docs_ids(docs, skill)
    ids = skill.documentations.ids
    if docs
      docs.each do |doc|
        doc_id = doc[:id].to_i
        ids.delete(doc_id) if ids.include? doc_id
      end
    end
    ids
  end

  def price_params(params)
    params.select { |key, _| key.to_s.ends_with? '_price' }
  end

  def destroy_unused_docs(docs, skill)
    Documentation.destroy_unused(redundant_docs_ids(docs, skill))
  end

  def destroy_unused_files
    DocumentationFile.destroy_unused
  end
end

以上是关于ruby skills_wizard.rb的主要内容,如果未能解决你的问题,请参考以下文章

Ruby运算符

Ruby 25 岁了!Ruby 之父说 Ruby 3 有望 3 倍提速

如何学习ruby?Ruby学习技巧分享

ruby Ruby脚本,看看是否用openssl编译了ruby

什么是ruby?

ruby和ruby ee