Sha256: b3fb5e153db88e1e20c362907760c16925116b30dd2f7d2a320b5c91763a1ab6

Contents?: true

Size: 1.3 KB

Versions: 3

Compression:

Stored size: 1.3 KB

Contents

require 'dice'
require 'gm/notepad/parameters/table_lookup'
require 'gm/notepad/evaluators/dice_evaluator'
module Gm
  module Notepad
    # Responsible for recording entries and then dumping them accordingly.
    class LineEvaluator
      def initialize(table_registry:)
        @table_registry = table_registry
      end
      attr_reader :table_registry

      TABLE_NAME_REGEXP = %r{(?<table_name_container>\{(?<table_name>[^\{\}]+)\})}
      def call(line:, expand_line: true)
        return line unless expand_line
        text = parse_table(text: line)
        parse_dice(text: text)
      end

      private

      def parse_table(text:)
        while match = text.match(TABLE_NAME_REGEXP)
          table_lookup = Parameters::TableLookup.new(text: match[:table_name].strip, roll_dice: true)
          entry = table_registry.lookup(**table_lookup.parameters)
          text = text.sub(match[:table_name_container], entry)
        end
        text
      end
      DICE_REGEXP = %r{(?<dice_container>\[(?<dice>[^\]]+)\])}
      def parse_dice(text:)
        while match = text.match(DICE_REGEXP)
          evaluated_dice = Evaluators::DiceEvaluator.call(text: match[:dice], fallback: "(#{match[:dice]})")
          text = text.sub(match[:dice_container], evaluated_dice)
        end
        text
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
gm-notepad-0.0.10 lib/gm/notepad/line_evaluator.rb
gm-notepad-0.0.9 lib/gm/notepad/line_evaluator.rb
gm-notepad-0.0.8 lib/gm/notepad/line_evaluator.rb