Class: MijDiscord::Events::EventBase

Inherits:
Object
  • Object
show all
Defined in:
lib/mij-discord/events.rb

Direct Known Subclasses

Generic

Defined Under Namespace

Classes: FilterMatch

Class Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ EventBase

Returns a new instance of EventBase.



7
8
9
# File 'lib/mij-discord/events.rb', line 7

def initialize(*args)
  # Nothing
end

Class Attribute Details

.event_filtersObject (readonly)

Returns the value of attribute event_filters.



74
75
76
# File 'lib/mij-discord/events.rb', line 74

def event_filters
  @event_filters
end

Class Method Details

.delegate_method(*names, to:) ⇒ Object



84
85
86
87
88
89
90
# File 'lib/mij-discord/events.rb', line 84

def delegate_method(*names, to:)
  names.each do |name|
    define_method(name) do |*arg|
      send(to).send(name, *arg)
    end
  end
end

.filter_match(key, field: key, on: :any, cmp: nil, &block) ⇒ Object

Raises:

  • (ArgumentError)


76
77
78
79
80
81
82
# File 'lib/mij-discord/events.rb', line 76

def filter_match(key, field: key, on: :any, cmp: nil, &block)
  raise ArgumentError, 'No comparison function provided' unless cmp || block

  # @event_filters ||= superclass&.event_filters&.dup || {}
  filter = (@event_filters[key] ||= [])
  filter << FilterMatch.new(field, on, block || cmp)
end

.inherited(sc) ⇒ Object



92
93
94
95
# File 'lib/mij-discord/events.rb', line 92

def inherited(sc)
  filters = @event_filters&.dup || {}
  sc.instance_variable_set(:@event_filters, filters)
end

Instance Method Details

#inspectObject



56
57
58
# File 'lib/mij-discord/events.rb', line 56

def inspect
  MijDiscord.make_inspect(self)
end

#trigger?(params) ⇒ Boolean

Returns:

  • (Boolean)


11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/mij-discord/events.rb', line 11

def trigger?(params)
  filters = self.class.event_filters

  result = params.map do |key, param|
    next true unless filters.has_key?(key)

    check = filters[key].map do |match|
      on, field, cmp = match.on, match.field, match.cmp

      is_match = case on
        when Array
          on.reduce(false) {|a,x| a || trigger_match?(x, param) }
        else
          trigger_match?(on, param)
      end

      next false unless is_match

      value = case field
        when Array
          field.reduce(self) {|a,x| a.respond_to?(x) ? a.send(x) : nil }
        else
          respond_to?(field) ? send(field) : nil
      end

      case cmp
        when :eql?
          value == param
        when :neq?
          value != param
        when :case
          param === value
        when Proc
          cmp.call(value, param)
        else
          false
      end
    end

    check.reduce(false, &:|)
  end

  result.reduce(true, &:&)
end