Class: Lich::Gemstone::PlaceholderTemplate

Inherits:
Object
  • Object
show all
Defined in:
documented/gemstone/creature.rb

Overview

Template string with placeholder substitution

Supports placeholders like Pronoun, direction, weapon that can be replaced with actual values or matched against game text. Implements regex caching for efficient repeated matching.

Instance Method Summary collapse

Constructor Details

#initialize(template, placeholders = {}) ⇒ PlaceholderTemplate

Initialize a placeholder template

Parameters:

  • template (String)

    Template string with placeholder markers

  • placeholders (Hash) (defaults to: {})

    Map of placeholder names to possible values



857
858
859
860
861
# File 'documented/gemstone/creature.rb', line 857

def initialize(template, placeholders = {})
  @template = template
  @placeholders = placeholders
  @regex_cache = {}
end

Instance Method Details

#placeholdersObject



867
868
869
# File 'documented/gemstone/creature.rb', line 867

def placeholders
  @placeholders
end

#templateObject



863
864
865
# File 'documented/gemstone/creature.rb', line 863

def template
  @template
end

#to_display(subs = {}) ⇒ Object



871
872
873
874
875
876
877
878
# File 'documented/gemstone/creature.rb', line 871

def to_display(subs = {})
  line = @template.dup
  @placeholders.each do |key, options|
    value = subs[key] || options.sample || ""
    line.gsub!("{#{key}}", value.to_s)
  end
  line
end

#to_regex(literals = {}) ⇒ Object



880
881
882
883
884
885
886
887
888
889
890
891
892
893
# File 'documented/gemstone/creature.rb', line 880

def to_regex(literals = {})
  # Use cache to avoid rebuilding regex on every call
  cache_key = literals.hash
  return @regex_cache[cache_key] if @regex_cache[cache_key]

  regex = if @template.is_a?(Array)
            regexes = @template.map { |t| self.class.new(t, @placeholders).to_regex(literals) }
            Regexp.union(*regexes)
          else
            build_regex(literals)
          end

  @regex_cache[cache_key] = regex
end