Sha256: fc651323ce71460f0ca9556642ddcb1bff1eff69739cd62c2cc1061b1b2cd080

Contents?: true

Size: 1.28 KB

Versions: 5

Compression:

Stored size: 1.28 KB

Contents

# Copyright (c) 2023 Jerome Arbez-Gindre
# frozen_string_literal: true

# :nocov:
require('asciidoctor/extensions') unless RUBY_ENGINE == 'opal'
# :nocov:

require('ostruct')

module Asciidoctor
  module Defmastership
    # Hosts several Text replacement rules
    class RegexpDispatcher
      # Class to link a regexp with a method
      Rule = Struct.new(:regexp, :method_symbol)
      private_constant :Rule

      # @param client [Object] the object that will receive method call on regexp matches
      def initialize(client)
        @client = client
        @rules = []
      end

      # Add a rule
      #
      # @param regexp [Regexp] the regexp for this rule
      # @param method_symbol [Symbol] the symbol for the method call
      # @return [RegexpDispatcher] self to allow add_rule calls chain
      def add_rule(regexp, method_symbol)
        @rules << Rule.new(regexp, method_symbol)
        self
      end

      # Add a rule
      #
      # @param line [String] the original line
      # @return [Array<String>] the lines to replace the original line
      def replace(line)
        @rules.each do |rule|
          matches = rule.regexp.match(line)
          return @client.public_send(rule.method_symbol, line, matches) if matches
        end
        [line]
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
asciidoctor-defmastership-1.3.0 lib/asciidoctor-defmastership/regexp_dispatcher.rb
asciidoctor-defmastership-1.2.0 lib/asciidoctor-defmastership/regexp_dispatcher.rb
asciidoctor-defmastership-1.1.2 lib/asciidoctor-defmastership/regexp_dispatcher.rb
asciidoctor-defmastership-1.1.1 lib/asciidoctor-defmastership/regexp_dispatcher.rb
asciidoctor-defmastership-1.1.0 lib/asciidoctor-defmastership/regexp_dispatcher.rb