Class: DelayHenka::ScheduledAction

Inherits:
ApplicationRecord show all
Defined in:
app/models/delay_henka/scheduled_action.rb

Constant Summary collapse

STATES =
{
  STAGED: 'staged',
  COMPLETED: 'completed',
  ERRORED: 'errored'
}

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.schedule(record:, method_name:, argument: nil, by_id:, schedule_at: Time.current) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'app/models/delay_henka/scheduled_action.rb', line 18

def self.schedule(record:, method_name:, argument: nil, by_id:, schedule_at: Time.current)
  Keka.run do
    begin
      arity = record.method(method_name.to_sym).arity
      Keka.err_unless! (arity == 0 && argument.nil?) || (arity == 1 && !argument.nil?), 'wrong arity'
      DelayHenka::ScheduledAction.create(
        actionable: record,
        method_name: method_name,
        argument: argument.to_json,
        submitted_by_id: by_id,
        schedule_at: schedule_at
      )
    rescue NameError => e
      Keka.err_if! true, e.message
    end
  end
end

Instance Method Details

#apply_actionObject



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'app/models/delay_henka/scheduled_action.rb', line 36

def apply_action
  unless actionable
    # Caution: model validations are bypassed
    update_columns(state: STATES[:ERRORED], error_message: 'Target record cannot be found')
    return
  end

  begin
    output = actionable.method(method_name.to_sym).arity == 0 ?
      actionable.send(method_name) :
      actionable.send(method_name, JSON.parse(argument))
    update!(state: STATES[:COMPLETED], return_value: output.to_json)
  rescue => e
    update!(state: STATES[:ERRORED], error_message: e.message)
    raise e
  end
end