Class: Bg::Deferrable

Inherits:
Object
  • Object
show all
Defined in:
lib/bg/deferrable.rb

Defined Under Namespace

Modules: Behavior

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(object, queue: :default, wait: 0) ⇒ Deferrable

Returns a new instance of Deferrable.

Raises:

  • (::ArgumentError)


30
31
32
33
34
35
# File 'lib/bg/deferrable.rb', line 30

def initialize(object, queue: :default, wait: 0)
  raise ::ArgumentError unless object.is_a?(::GlobalID::Identification)
  @object = object
  @queue  = queue || :default
  @wait   = wait.to_i
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/bg/deferrable.rb', line 37

def method_missing(name, *args)
  if @object.respond_to? name
    raise ::ArgumentError.new("blocks are not supported") if block_given?
    begin
      queue_args = { queue: @queue }
      queue_args[:wait] = @wait if @wait > 0
      job = ::Bg::DeferredMethodCallJob.set(**queue_args).perform_later @object, name.to_s, *self.class.make_enqueable(args)
    rescue ::StandardError => e
      raise ::ArgumentError.new("Failed to background method call! <#{@object.class.name}##{name}> #{e.message}")
    ensure
      return job
    end
  end
  super
end

Class Method Details

.make_enqueable(value) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/bg/deferrable.rb', line 13

def self.make_enqueable(value)
  case value
  when ::Hash then
    value.each.with_object({}) do |(key, val), memo|
      memo[key.to_s] = make_enqueable(val)
    end
  when ::Array then
    value.map { |val| make_enqueable val }
  when ::Symbol then
    value.to_s
  when ::Date, ::Time, ::DateTime then
    value.respond_to?(:iso8601) ? value.iso8601 : value.to_s
  else
    value
  end
end

Instance Method Details

#respond_to?(name) ⇒ Boolean

Returns:

  • (Boolean)


53
54
55
56
# File 'lib/bg/deferrable.rb', line 53

def respond_to?(name)
  return true if @object.respond_to? name
  super
end