Class: Ductwork::Context

Inherits:
Object
  • Object
show all
Defined in:
lib/ductwork/context.rb

Defined Under Namespace

Classes: OverwriteError

Instance Method Summary collapse

Constructor Details

#initialize(run_id) ⇒ Context

Returns a new instance of Context.



7
8
9
# File 'lib/ductwork/context.rb', line 7

def initialize(run_id)
  @run_id = run_id
end

Instance Method Details

#get(key) ⇒ Object

Raises:

  • (ArgumentError)


11
12
13
14
15
16
17
18
# File 'lib/ductwork/context.rb', line 11

def get(key)
  raise ArgumentError, "Key must be a string" if !key.is_a?(String)

  Ductwork::Tuple
    .select(:serialized_value)
    .find_by(run_id:, key:)
    &.value
end

#set(key, value, overwrite: false) ⇒ Object



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
# File 'lib/ductwork/context.rb', line 20

def set(key, value, overwrite: false)
  attributes = {
    id: SecureRandom.uuid_v7,
    run_id: run_id,
    key: key,
    serialized_value: Ductwork::Tuple.serialize(value),
    first_set_at: Time.current,
    last_set_at: Time.current,
  }
  opts = if Ductwork::Tuple.connection.adapter_name.match?(/mysql|trilogy/i)
           {}
         else
           { unique_by: %i[run_id key] }
         end

  if overwrite
    Ductwork::Tuple.upsert(attributes, **opts)
  else
    begin
      Ductwork::Tuple.create!(attributes)
    rescue ActiveRecord::RecordNotUnique
      raise Ductwork::Context::OverwriteError, "Can only set value once"
    end
  end

  value
end