Class: Lich::Gemstone::PlaceholderTemplate
- Inherits:
-
Object
- Object
- Lich::Gemstone::PlaceholderTemplate
- Defined in:
- documented/gemstone/creature.rb
Overview
Renders and matches dynamic message templates with placeholder substitution.
Used by Messaging to support dynamic text: templates contain placeholders like pronoun, direction, and weapon which are substituted with game values at display time. Supports random variation when substitutions are not provided, regex matching to extract captured groups, and caching of compiled regexes for performance.
Instance Method Summary collapse
-
#initialize(template, placeholders = {}) ⇒ void
constructor
Initializes a placeholder template and caches for rendering/matching.
-
#placeholders ⇒ Hash
Returns the placeholder definitions.
-
#template ⇒ String
Returns the template string.
-
#to_display(subs = {}) ⇒ String
Renders the template with placeholders substituted or filled randomly.
-
#to_regex(literals = {}) ⇒ Regexp
Compiles the template to a regex pattern for matching.
Constructor Details
#initialize(template, placeholders = {}) ⇒ void
Initializes a placeholder template and caches for rendering/matching.
844 845 846 847 848 |
# File 'documented/gemstone/creature.rb', line 844 def initialize(template, placeholders = {}) @template = template @placeholders = placeholders @regex_cache = {} end |
Instance Method Details
#placeholders ⇒ Hash
Returns the placeholder definitions.
860 861 862 |
# File 'documented/gemstone/creature.rb', line 860 def placeholders @placeholders end |
#template ⇒ String
Returns the template string.
853 854 855 |
# File 'documented/gemstone/creature.rb', line 853 def template @template end |
#to_display(subs = {}) ⇒ String
Renders the template with placeholders substituted or filled randomly.
For each placeholder, uses the supplied substitution value if present, otherwise picks a random option from the placeholder definition, defaulting to an empty string if no options exist.
877 878 879 880 881 882 883 884 |
# File 'documented/gemstone/creature.rb', line 877 def to_display(subs = {}) line = @template.dup @placeholders.each do |key, | value = subs[key] || .sample || "" line.gsub!("{#{key}}", value.to_s) end line end |
#to_regex(literals = {}) ⇒ Regexp
Compiles the template to a regex pattern for matching.
Converts the template string to a regex where each placeholder becomes a named capture group or raw regex pattern. Results are cached by substitution hash to avoid rebuilding on repeated calls.
900 901 902 903 904 905 906 907 908 909 910 911 912 913 |
# File 'documented/gemstone/creature.rb', line 900 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 |