Class: Decidim::DecidimAwesome::Admin::UpdateConfig

Inherits:
Command
  • Object
show all
Defined in:
app/commands/decidim/decidim_awesome/admin/update_config.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(form) ⇒ UpdateConfig

Public: Initializes the command.

form - A config form



10
11
12
# File 'app/commands/decidim/decidim_awesome/admin/update_config.rb', line 10

def initialize(form)
  @form = form
end

Instance Attribute Details

#formObject (readonly)

Returns the value of attribute form.



54
55
56
# File 'app/commands/decidim/decidim_awesome/admin/update_config.rb', line 54

def form
  @form
end

Instance Method Details

#callObject

Executes the command. Broadcasts these events:

  • :ok when everything is valid.

  • :invalid if we couldn’t proceed.

Returns nothing.



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'app/commands/decidim/decidim_awesome/admin/update_config.rb', line 20

def call
  if form.invalid?
    message = form.errors[:scoped_styles].join("; ") if @form.errors[:scoped_styles].any?
    message = form.errors[:scoped_admins].join("; ") if @form.errors[:scoped_admins].any?
    return broadcast(:invalid, message, form.errors)
  end

  begin
    form.attributes.each do |key, val|
      # ignore nil attributes (must specifically be set to false if necessary)
      next unless form.valid_keys.include?(key.to_sym)

      setting = AwesomeConfig.find_or_initialize_by(var: key, organization: form.current_organization)

      value = if form.respond_to?("#{key}_attributes")
                # for complex cases
                form.public_send("#{key}_attributes")
              elsif val.respond_to?(:attributes)
                # when the value is another form
                val.attributes
              else
                val
              end

      setting.value = value
      setting.save!
    end

    broadcast(:ok)
  rescue ActiveRecord::RecordInvalid => e
    broadcast(:invalid, e.message)
  end
end