Sha256: bb44fd3e2b6169ca32d23d60251ea4b0cd16ad789caf89ee21b9d59f310ff792

Contents?: true

Size: 1.06 KB

Versions: 22

Compression:

Stored size: 1.06 KB

Contents

# frozen_string_literal: true

module Alchemy
  class DeleteElements
    class WouldLeaveOrphansError < StandardError; end
    attr_reader :elements

    def initialize(elements)
      @elements = elements
    end

    def call
      if orphanable_records.present?
        raise WouldLeaveOrphansError
      end

      contents = Alchemy::Content.where(element_id: elements.map(&:id))
      contents.group_by(&:essence_type)
        .transform_values! { |value| value.map(&:essence_id) }
        .each do |class_name, ids|
          class_name.constantize.where(id: ids).delete_all
        end
      contents.delete_all
      delete_elements
    end

    private

    def orphanable_records
      Alchemy::Element.where(parent_element_id: [elements]).where.not(id: elements)
    end

    def delete_elements
      case elements
      when ActiveRecord::Associations::CollectionProxy
        elements.delete_all(:delete_all)
      when ActiveRecord::Relation
        elements.delete_all
      else
        Alchemy::Element.where(id: elements).delete_all
      end
    end
  end
end

Version data entries

22 entries across 22 versions & 1 rubygems

Version Path
alchemy_cms-6.0.8 app/services/alchemy/delete_elements.rb
alchemy_cms-6.0.7 app/services/alchemy/delete_elements.rb
alchemy_cms-6.0.6 app/services/alchemy/delete_elements.rb
alchemy_cms-6.0.5 app/services/alchemy/delete_elements.rb
alchemy_cms-6.0.4 app/services/alchemy/delete_elements.rb
alchemy_cms-6.0.3 app/services/alchemy/delete_elements.rb
alchemy_cms-6.0.2 app/services/alchemy/delete_elements.rb
alchemy_cms-6.0.1 app/services/alchemy/delete_elements.rb
alchemy_cms-6.0.0 app/services/alchemy/delete_elements.rb
alchemy_cms-6.0.0.pre.rc7 app/services/alchemy/delete_elements.rb
alchemy_cms-6.0.0.pre.rc6 app/services/alchemy/delete_elements.rb
alchemy_cms-6.0.0.pre.rc5 app/services/alchemy/delete_elements.rb
alchemy_cms-6.0.0.pre.rc4 app/services/alchemy/delete_elements.rb
alchemy_cms-6.0.0.pre.rc3 app/services/alchemy/delete_elements.rb
alchemy_cms-6.0.0.pre.rc2 app/services/alchemy/delete_elements.rb
alchemy_cms-6.0.0.pre.rc1 app/services/alchemy/delete_elements.rb
alchemy_cms-6.0.0.pre.b6 app/services/alchemy/delete_elements.rb
alchemy_cms-6.0.0.pre.b5 app/services/alchemy/delete_elements.rb
alchemy_cms-6.0.0.pre.b4 app/services/alchemy/delete_elements.rb
alchemy_cms-6.0.0.b3 app/services/alchemy/delete_elements.rb