Class: Cosmo::Job::Data

Inherits:
Object
  • Object
show all
Defined in:
lib/cosmo/job/data.rb

Constant Summary collapse

DEFAULTS =
{ stream: :default, retry: 3, dead: true }.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(class_name, args, options = nil) ⇒ Data

Returns a new instance of Data.



12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/cosmo/job/data.rb', line 12

def initialize(class_name, args, options = nil)
  @class_name = class_name
  @args = args
  @options = Hash(options)
  validate!

  @at = @options[:at].to_i if @options[:at]
  @at ||= Time.now.to_i + @options[:in].to_i if @options[:in]
  @subject = @options[:subject] if @options[:subject]

  @jid = SecureRandom.hex(12)
end

Instance Attribute Details

#jidObject (readonly)

Returns the value of attribute jid.



10
11
12
# File 'lib/cosmo/job/data.rb', line 10

def jid
  @jid
end

Instance Method Details

#as_jsonObject



35
36
37
38
39
40
41
42
43
# File 'lib/cosmo/job/data.rb', line 35

def as_json
  {
    jid: jid,
    class: @class_name,
    args: @args,
    retry: retries,
    dead: dead
  }
end

#stream(target: false) ⇒ Object



25
26
27
28
29
# File 'lib/cosmo/job/data.rb', line 25

def stream(target: false)
  return @options[:stream] if target

  @at ? :scheduled : @options[:stream]
end

#subject(target: false) ⇒ Object



31
32
33
# File 'lib/cosmo/job/data.rb', line 31

def subject(target: false)
  ["jobs", stream(target:).to_s, Utils::String.underscore(@class_name)]
end

#to_argsObject



49
50
51
52
53
54
55
56
57
# File 'lib/cosmo/job/data.rb', line 49

def to_args
  headers = { "Nats-Msg-Id" => jid }
  if @at
    headers.merge!("X-Execute-At" => @at.to_i,
                   "X-Stream" => stream(target: true),
                   "X-Subject" => subject(target: true).join("."))
  end
  [@subject || subject.join("."), to_json, { stream: stream, header: headers }]
end

#to_json(*_args) ⇒ Object



45
46
47
# File 'lib/cosmo/job/data.rb', line 45

def to_json(*_args)
  Utils::Json.dump(as_json)
end