File: events.rb

package info (click to toggle)
ruby-wisper 3.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 276 kB
  • sloc: ruby: 1,231; makefile: 4
file content (61 lines) | stat: -rw-r--r-- 1,567 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
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
55
56
57
58
59
60
61
module Wisper
  module ValueObjects #:nodoc:
    # Describes allowed events
    #
    # Duck-types the argument to quack like array of strings
    # when responding to the {#include?} method call.
    class Events

      # @!scope class
      # @!method new(on)
      # Initializes a 'list' of events
      #
      # @param [NilClass, String, Symbol, Array, Regexp] list
      #
      # @raise [ArgumentError]
      #   if an argument if of unsupported type
      #
      # @return [undefined]
      def initialize(list)
        @list = list
      end

      # Check if given event is 'included' to the 'list' of events
      #
      # @param [#to_s] event
      #
      # @return [Boolean]
      def include?(event)
        appropriate_method.call(event.to_s)
      end

      private

      def methods
        {
          NilClass   => ->(_event) { true },
          String     => ->(event)  { list == event },
          Symbol     => ->(event)  { list.to_s == event },
          Enumerable => ->(event)  { list.map(&:to_s).include? event },
          Regexp     => ->(event)  { list.match(event) || false }
        }
      end

      def list
        @list
      end

      def appropriate_method
        @appropriate_method ||= methods[recognized_type]
      end

      def recognized_type
        methods.keys.detect(&list.method(:is_a?)) || type_not_recognized
      end

      def type_not_recognized
        fail(ArgumentError, "#{list.class} not supported for `on` argument")
      end
    end # class Events
  end # module ValueObjects
end # module Wisper