Module: Rails::GraphQL::Helpers::WithEvents

Included in:
Directive, Field::OutputField, Source
Defined in:
lib/rails/graphql/helpers/with_events.rb

Overview

Helper module that allows other objects to hold events, either from a singleton point-of-view, or for instances

Defined Under Namespace

Modules: FixedTypes

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extended(other) ⇒ Object



9
10
11
12
13
14
15
# File 'lib/rails/graphql/helpers/with_events.rb', line 9

def self.extended(other)
  other.extend(Helpers::InheritedCollection)
  other.extend(WithEvents::FixedTypes)

  other.inherited_collection(:events, type: :hash_array)
  other.inherited_collection(:listeners)
end

.included(other) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/rails/graphql/helpers/with_events.rb', line 17

def self.included(other)
  other.extend(WithEvents::FixedTypes)
  other.delegate(:event_types, to: :class)

  other.define_method(:events) { @events ||= Hash.new { |h, k| h[k] = [] } }
  other.define_method(:all_events) { @events if defined?(@events) }
  other.define_method(:events?) { defined?(@events) && @events.present? }

  other.define_method(:listeners) { @listeners ||= Set.new }
  other.define_method(:all_listeners) { @listeners if defined?(@listeners) }
  other.define_method(:listeners?) { defined?(@listeners) && @listeners.present? }
end

Instance Method Details

#on(event_name, callback = nil, unshift: false, &block) ⇒ Object

Add a new event listener for the given event_name. It is possible to prepend the event by setting unshift: true. This checks if the event name is a valid one due to event_types.

Raises:



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/rails/graphql/helpers/with_events.rb', line 61

def on(event_name, callback = nil, unshift: false, &block)
  event_name = event_name.to_sym
  valid = !event_types || event_types.include?(event_name)
  raise ArgumentError, (+<<~MSG).squish unless valid
    The #{event_name} is not a valid event type.
  MSG

  invalid_callback = callback.nil? || callback.is_a?(Callback)
  raise ArgumentError, (+<<~MSG).squish unless invalid_callback
    The provided #{callback.class.name} is not a valid callback.
  MSG

  listeners << event_name
  events[event_name].send(unshift ? :unshift : :push, callback || block)
  self
end