Sha256: 6e45f3fa2f13a2b3d37ad63664b3eb71fff5fe46436e151907e832b6d5b644fe

Contents?: true

Size: 1.16 KB

Versions: 4

Compression:

Stored size: 1.16 KB

Contents

# frozen_string_literal: true
module Decidim
  module Admin
    # A command that reorders the steps in a participatory process.
    class ReorderParticipatoryProcessSteps < Rectify::Command
      # Public: Initializes the command.
      #
      # collection - an ActiveRecord::Relation of steps
      # order - an Array holding the order of IDs of steps
      def initialize(collection, order)
        @collection = collection
        @order = order
      end

      # Executes the command. Braodcasts these events:
      #
      # - :ok when everything is valid.
      # - :invalid if the data wasn't valid and we couldn't proceed.
      #
      # Returns nothing.
      def call
        return broadcast(:invalid) unless order.present?

        reorder_steps
        broadcast(:ok)
      end

      private

      attr_reader :collection

      def reorder_steps
        data = order.each_with_index.inject({}) do |hash, (id, index)|
          hash.update(id => { position: index })
        end

        collection.update(data.keys, data.values)
      end

      def order
        return nil unless @order.is_a?(Array) && @order.present?

        @order
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 2 rubygems

Version Path
decidim-admin-0.0.1.alpha9 app/commands/decidim/admin/reorder_participatory_process_steps.rb
decidim-0.0.1.alpha9 decidim-admin/app/commands/decidim/admin/reorder_participatory_process_steps.rb
decidim-admin-0.0.1.alpha8 app/commands/decidim/admin/reorder_participatory_process_steps.rb
decidim-0.0.1.alpha8 decidim-admin/app/commands/decidim/admin/reorder_participatory_process_steps.rb