Class: Debounced::Callback

Inherits:
Object
  • Object
show all
Defined in:
lib/debounced/callback.rb

Overview

Represents a callback to be executed by the debounce service

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(class_name:, method_name:, args: [], kwargs: {}) ⇒ Callback

Note:

if the class implements the method_name, the message will be sent to the class with the args and kwargs.

otherwise, an instance of the class will be created and the message will be sent to the instance. in this case, the args and kwargs will be passed to the initializer.

Parameters:

  • class_name (String)

    the name of the class that will receive the callback

  • method_name (String)

    the name of the method that will be called

  • args (Array) (defaults to: [])

    the positional arguments to be passed to the method (optional)

  • kwargs (Hash) (defaults to: {})

    the keyword arguments to be passed to the method (optional)



17
18
19
20
21
22
# File 'lib/debounced/callback.rb', line 17

def initialize(class_name:, method_name:, args: [], kwargs: {})
  @class_name = class_name.to_s
  @method_name = method_name.to_s
  @args = args
  @kwargs = kwargs
end

Instance Attribute Details

#argsObject

Returns the value of attribute args.



6
7
8
# File 'lib/debounced/callback.rb', line 6

def args
  @args
end

#class_nameObject

Returns the value of attribute class_name.



6
7
8
# File 'lib/debounced/callback.rb', line 6

def class_name
  @class_name
end

#kwargsObject

Returns the value of attribute kwargs.



6
7
8
# File 'lib/debounced/callback.rb', line 6

def kwargs
  @kwargs
end

#method_nameObject

Returns the value of attribute method_name.



6
7
8
# File 'lib/debounced/callback.rb', line 6

def method_name
  @method_name
end

Class Method Details

.parse(data) ⇒ Object



24
25
26
27
28
29
30
31
# File 'lib/debounced/callback.rb', line 24

def self.parse(data)
  new(
    class_name: data['class_name'],
    method_name: data['method_name'],
    args: data['args'],
    kwargs: data['kwargs'].transform_keys(&:to_sym),
  )
end

Instance Method Details

#as_jsonObject



33
34
35
36
37
38
39
40
# File 'lib/debounced/callback.rb', line 33

def as_json
  {
    class_name:,
    method_name:,
    args:,
    kwargs:,
  }
end

#callObject



42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/debounced/callback.rb', line 42

def call
  Debounced.configuration.logger.debug("Invoking callback #{method_name}")
  klass = Object.const_get(class_name)
  if klass.respond_to?(method_name)
    klass.send(method_name, *args, **kwargs)
  else
    instance = klass.new(*args, **kwargs)
    instance.send(method_name)
  end
rescue StandardError => e
  Debounced.configuration.logger.warn("Unable to invoke callback #{as_json}: #{e.message}")
  Debounced.configuration.logger.warn(e.backtrace.join("\n"))
end