Class: LcpRuby::Actions::ActionExecutor

Inherits:
Object
  • Object
show all
Defined in:
lib/lcp_ruby/actions/action_executor.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(action_key, context = {}) ⇒ ActionExecutor

Returns a new instance of ActionExecutor.



6
7
8
9
# File 'lib/lcp_ruby/actions/action_executor.rb', line 6

def initialize(action_key, context = {})
  @action_key = action_key.to_s
  @context = context
end

Instance Attribute Details

#action_keyObject (readonly)

Returns the value of attribute action_key.



4
5
6
# File 'lib/lcp_ruby/actions/action_executor.rb', line 4

def action_key
  @action_key
end

#contextObject (readonly)

Returns the value of attribute context.



4
5
6
# File 'lib/lcp_ruby/actions/action_executor.rb', line 4

def context
  @context
end

Instance Method Details

#executeObject



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/lcp_ruby/actions/action_executor.rb', line 11

def execute
  action_class = ActionRegistry.action_for(action_key)
  raise Error, "Action '#{action_key}' not found" unless action_class

  record = context[:record]
  user = context[:current_user]

  return Actions::Result.unauthorized unless action_class.authorized?(record, user)

  if context[:async] && defined?(LcpRuby::BackgroundJobs) && LcpRuby::BackgroundJobs.respond_to?(:enqueue)
    return enqueue_async(record, user)
  end

  action = action_class.new(context)
  action.call
rescue StandardError => e
  Actions::Result.new(
    success: false,
    message: I18n.t("lcp_ruby.actions.execution_failed",
                    reason: e.message,
                    default: "Action failed: %{reason}"),
    redirect_to: nil,
    data: nil,
    errors: [ e.message ]
  )
end