Class: Markbridge::Processors::DiscourseMarkdown::Detectors::Mention

Inherits:
Base
  • Object
show all
Defined in:
lib/markbridge/processors/discourse_markdown/detectors/mention.rb

Overview

Detects user and group mentions (@username, @groupname).

Examples:

Basic usage

detector = Mention.new
match = detector.detect("Hello @gerhard!", 6)
match.node.name # => "gerhard"
match.node.type # => :user (default)

With type resolver

resolver = ->(name) { name == "Testers" ? :group : :user }
detector = Mention.new(type_resolver: resolver)
match = detector.detect("@Testers", 0)
match.node.type # => :group

Instance Method Summary collapse

Constructor Details

#initialize(type_resolver: nil) ⇒ Mention

Returns a new instance of Mention.

Parameters:

  • type_resolver (#call, nil) (defaults to: nil)

    callable that takes a name and returns :user or :group



22
23
24
# File 'lib/markbridge/processors/discourse_markdown/detectors/mention.rb', line 22

def initialize(type_resolver: nil)
  @type_resolver = type_resolver
end

Instance Method Details

#detect(input, pos) ⇒ Match?

Attempt to detect a mention at the given position.

Parameters:

  • input (String)

    the full input string

  • pos (Integer)

    current position to check

Returns:

  • (Match, nil)

    match result or nil if no match



31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/markbridge/processors/discourse_markdown/detectors/mention.rb', line 31

def detect(input, pos)
  return nil unless input[pos] == "@"
  return nil unless word_boundary?(input, pos)

  # Extract the username/group name
  name = extract_word(input, pos + 1)
  return nil if name.empty?

  end_pos = pos + 1 + name.length
  type = resolve_type(name)
  node = AST::Mention.new(name:, type:)

  Match.new(start_pos: pos, end_pos:, node:)
end