Sha256: 4ce4f9d01daf55fb7eeb907005f2ee7233303e90507593df2e2db950af4701bc

Contents?: true

Size: 1.64 KB

Versions: 5

Compression:

Stored size: 1.64 KB

Contents

# frozen_string_literal: true

module Decidim
  module DecidimAwesome
    module Admin
      class RenameScopeLabel < Rectify::Command
        # Public: Initializes the command.
        #
        # params - A constraint params
        def initialize(params, organization)
          @text = params[:text]&.strip&.gsub(" ", "_")&.parameterize&.truncate(64)
          @scope = params[:scope]
          @key = params[:key]
          @attribute = params[:attribute]
          @organization = organization
        end

        # Executes the command. Broadcasts these events:
        #
        # - :ok when everything is valid.
        # - :invalid if we couldn't proceed.
        #
        # Returns nothing.
        def call
          raise StandardError, "empty value" if @text.blank?
          raise StandardError, "key already exists" if config.value.keys.include? @text

          transaction do
            config.value[@text] = config.value.delete @key
            config.save!
            if config_scope
              config_scope.var = scope
              config_scope.save!
            end
          end

          broadcast(:ok, { scope: scope, key: @text })
        rescue StandardError => e
          broadcast(:invalid, e.message)
        end

        private

        def scope
          @scope.gsub(/_#{@key}$/, "_#{@text}")
        end

        def config
          @config ||= Decidim::DecidimAwesome::AwesomeConfig.find_by!(var: @attribute, organization: @organization)
        end

        def config_scope
          @config_scope ||= Decidim::DecidimAwesome::AwesomeConfig.find_by(var: @scope, organization: @organization)
        end
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
decidim-decidim_awesome-0.8.3 app/commands/decidim/decidim_awesome/admin/rename_scope_label.rb
decidim-decidim_awesome-0.8.2 app/commands/decidim/decidim_awesome/admin/rename_scope_label.rb
decidim-decidim_awesome-0.8.1 app/commands/decidim/decidim_awesome/admin/rename_scope_label.rb
decidim-decidim_awesome-0.8.0 app/commands/decidim/decidim_awesome/admin/rename_scope_label.rb
decidim-decidim_awesome-0.7.2 app/commands/decidim/decidim_awesome/admin/rename_scope_label.rb