# 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] 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