Commands

A command is custom class that manages the logic between your input, usually a form object, an object and an user.

Usually, a command is used to create, update or delete a object.

Commands are located in the app/commands/decidim/<my_module> directory, and named: <action>_<my_resource>.rb.

In the below example, you will be able to see how the command (CreateMyResource), events (Decidim::MyModule::MyResourceEvent) and jobs (Decidim::MyModule::MyCustomJob) can be used.

# frozen_string_literal: true

# app/commands/decidim/my_module/create_my_resource.rb
module Decidim
  module MyModule
    # A command with the business logic to create a resource.
    class CreateMyResource < Decidim::Command
      # Public: Initializes the command.
      #
      def initialize(form, resource)
        @form = form
        @resource = resource
      end

      def call
      return broadcast(:invalid) if form.invalid?

      transation do
         create_resource
         dispatch_event
         process_jobs
      end
      broadcast(:ok)
    end

      private

      attr_reader :form, :resource

      def process_jobs
      Decidim::MyModule::MyCustomJob.perform_later(resource)
    end

      def dispatch_event
        Decidim::EventsManager.publish(
          event: "decidim.events.my_module.my_resource_created",
          event_class: Decidim::MyModule::MyResourceEvent,
          resource:
        )
    end

      def create_resource
      @resource = Decidim.traceability.create!(
        resource,
        form.current_user,
        **attributes,
        visibility: "public-only"
      )
    end

      # this is mapping of
      # ActiveRecord::attribute => form.attribute
      def attributes
      {
        title: form.title,
        description: form.description,
        resource: form.resource
      }
    end
    end
  end
end

Sometimes you may need to extend a Decidim supplied command, then you can either override the attributes method, either extend it with a super call.

# frozen_string_literal: true

# app/lib/overrides/commands/create_my_resource.rb
module Decidim
  module Overrides
    module Commands
      module CreateMyResource
        def attributes
          super.merge(
            {
              my_custom_attribute: form.my_custom_attribute
            }
          )
        end
      end
    end
  end
end

Decidim::MyModule::CreateMyResource.prepend(Decidim::Overrides::Commands::CreateMyResource)

More information

  • Decidim::Command is an internalization of Rectify gem created by Andy Pike