File: event.rb

package info (click to toggle)
ruby-cucumber-core 16.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 764 kB
  • sloc: ruby: 5,074; makefile: 2
file content (59 lines) | stat: -rw-r--r-- 1,688 bytes parent folder | download
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
# frozen_string_literal: true

module Cucumber
  module Core
    class Event
      # Macro to generate new subclasses of {Event} with attribute readers.
      def self.new(*events)
        # Use normal constructor for subclasses of Event
        return super if ancestors.index(Event).positive?

        Class.new(Event) do
          # NB: We need to use metaprogramming here instead of direct variable obtainment
          # because JRuby does not guarantee the order in which variables are defined is equivalent
          # to the order in which they are obtainable
          #
          # See https://github.com/jruby/jruby/issues/7988 for more info
          attr_reader(*events)

          define_method(:initialize) do |*attributes|
            events.zip(attributes) do |name, value|
              instance_variable_set(:"@#{name}", value)
            end
          end

          define_method(:attributes) do
            events.map { |var| instance_variable_get(:"@#{var}") }
          end

          define_method(:to_h) do
            events.zip(attributes).to_h
          end

          def event_id
            self.class.event_id
          end
        end
      end

      class << self
        # @return [Symbol] the underscored name of the class to be used as the key in an event registry
        def event_id
          underscore(name.split('::').last).to_sym
        end

        private

        def underscore(string)
          string
            .to_s
            .gsub('::', '/')
            .gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
            .gsub(/([a-z\d])([A-Z])/, '\1_\2')
            .tr('-', '_')
            .downcase
        end
      end
    end
  end
end