Module: Cuniculus::Worker

Defined in:
lib/cuniculus/worker.rb

Constant Summary collapse

DEFAULT_OPTS =
{ queue: "cun_default" }.freeze
VALID_OPT_KEYS =
%i[queue].freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#cun_optsObject (readonly)

Returns the value of attribute cun_opts.



21
22
23
# File 'lib/cuniculus/worker.rb', line 21

def cun_opts
  @cun_opts
end

Class Method Details

.extended(base) ⇒ Object



11
12
13
14
# File 'lib/cuniculus/worker.rb', line 11

def self.extended(base)
  base.instance_variable_set(:@cun_opts, DEFAULT_OPTS)
  super
end

Instance Method Details

#cuniculus_options(opts) ⇒ Object

Worker-specific options for running cuniculus.

Note that options set on a worker class are inherited by its subclasses.

Examples:

Change the queue name of a worker

class MyWorker
  include Cuniculus::Worker

  cuniculus_options queue: "critical"

  def perform
    # run the task
  end
end

Parameters:

  • opts (Hash)

Options Hash (opts):

  • "queue" (String) — default: "cun_default"

    Name of the underlying RabbitMQ queue.



40
41
42
43
# File 'lib/cuniculus/worker.rb', line 40

def cuniculus_options(opts)
  opts = validate_opts!(opts)
  @cun_opts = opts
end

#inherited(mod) ⇒ Object



16
17
18
19
# File 'lib/cuniculus/worker.rb', line 16

def inherited(mod)
  mod.instance_variable_set(:@cun_opts, @cun_opts)
  super
end

#normalize_item(item) ⇒ Object



62
63
64
# File 'lib/cuniculus/worker.rb', line 62

def normalize_item(item)
  Cuniculus.dump_job(item)
end

#perform_async(*args) ⇒ Object



52
53
54
# File 'lib/cuniculus/worker.rb', line 52

def perform_async(*args)
  publish({ "class" => self, "args" => args })
end

#publish(item) ⇒ Object



56
57
58
59
60
# File 'lib/cuniculus/worker.rb', line 56

def publish(item)
  routing_key = cun_opts[:queue]
  payload = normalize_item(item)
  Cuniculus.enqueue [Cuniculus::CUNICULUS_EXCHANGE, payload, routing_key]
end

#validate_opts!(opts) ⇒ Object

Raises:

  • (Cuniculus::WorkerOptionsError)


45
46
47
48
49
50
# File 'lib/cuniculus/worker.rb', line 45

def validate_opts!(opts)
  raise Cuniculus::WorkerOptionsError, "Argument passed to 'cuniculus_options' should be a Hash" unless opts.is_a?(Hash)
  invalid_keys = opts.keys - VALID_OPT_KEYS
  raise Cuniculus::WorkerOptionsError, "Invalid keys passed to 'cuniculus_options': #{invalid_keys.inspect}" unless invalid_keys.empty?
  opts
end