Class: Lich::Gemstone::PlaceholderTemplate

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

Overview

Represents a template with placeholders for dynamic content.

Instance Method Summary collapse

Constructor Details

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

Initializes a new placeholder template with the given template and placeholders.

Parameters:

  • template (String)

    the template string

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

    a hash of placeholders and their options



736
737
738
739
740
# File 'documented/gemstone/creature.rb', line 736

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

Instance Method Details

#placeholdersObject



746
747
748
# File 'documented/gemstone/creature.rb', line 746

def placeholders
  @placeholders
end

#templateObject



742
743
744
# File 'documented/gemstone/creature.rb', line 742

def template
  @template
end

#to_display(subs = {}) ⇒ Object



750
751
752
753
754
755
756
757
# File 'documented/gemstone/creature.rb', line 750

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



759
760
761
762
763
764
765
766
767
768
769
770
771
772
# File 'documented/gemstone/creature.rb', line 759

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