Class: Jsapi::Controller::Methods::Callbacks::Callback

Inherits:
Object
  • Object
show all
Defined in:
lib/jsapi/controller/methods/callbacks/callback.rb

Overview

Represents a callback to be triggered.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(method_or_proc, **options) ⇒ Callback

Creates a callback that executes method_or_proc.

The following options can be specified:

  • :if - The conditions under which the callback is triggered only.

  • :unless - The conditions under which the callback isn’t triggered.

  • :only - The operations on which the callback is triggered only.

  • :except - The operations on which the callback isn’t triggered.

:if and :unless can be a symbol, a Proc or an array of symbols and Procs.



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/jsapi/controller/methods/callbacks/callback.rb', line 23

def initialize(method_or_proc, **options)
  @method_or_proc = method_or_proc

  @if, @unless =
    %i[if unless].map do |key|
      value = options[key]
      Array.wrap(value) if value
    end

  @only, @except =
    %i[only except].map do |key|
      value = options[key]
      Array.wrap(value).map(&:to_s) if value
    end
end

Instance Attribute Details

#method_or_procObject (readonly)

The method or Proc to be called.



10
11
12
# File 'lib/jsapi/controller/methods/callbacks/callback.rb', line 10

def method_or_proc
  @method_or_proc
end

Instance Method Details

#inspectObject

:nodoc:



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/jsapi/controller/methods/callbacks/callback.rb', line 39

def inspect # :nodoc:
  "#<#{self.class} #{@method_or_proc.inspect}#{
    {
      if: @if,
      unless: @unless,
      only: @only,
      except: @except
    }.filter_map do |key, value|
      next if value.nil?

      value = value.sole if value.one?
      ", #{key}: #{value.inspect}"
    end.join
  }>"
end

#skip_on?(controller, operation_name) ⇒ Boolean

Returns true if and only if the callback must not be triggered on controller and operation_name.

Returns:

  • (Boolean)


57
58
59
60
61
62
63
64
65
# File 'lib/jsapi/controller/methods/callbacks/callback.rb', line 57

def skip_on?(controller, operation_name)
  operation_name = operation_name.to_s

  @only&.exclude?(operation_name) ||
    @except&.include?(operation_name) ||
    @if&.any? { |condition| !evaluate(condition, controller) } ||
    @unless&.any? { |condition| evaluate(condition, controller) } ||
    false
end