Sha256: ec373bbb71333415dd5f1bd336d8d23dd24e16db54d33d0cb3bd51255f2c2e9e

Contents?: true

Size: 1.6 KB

Versions: 1

Compression:

Stored size: 1.6 KB

Contents

require 'dice'
require 'gm/notepad/parameters/table_lookup'
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)
          if table_lookup.index
            if index = Dice.parse(table_lookup.index)
              table_lookup.index = index.evaluate
            end
            entry = table_registry.lookup(index: table_lookup.index, table_name: table_lookup.table_name)
          else
            entry = table_registry.lookup(table_name: table_lookup.table_name)
          end
          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)
          if parsed_dice = Dice.parse(match[:dice])
            evaluated_dice = "#{parsed_dice.evaluate}"
          else
            evaluated_dice = "(#{match[:dice]})"
          end
          text = text.sub(match[:dice_container], evaluated_dice)
        end
        text
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
gm-notepad-0.0.6 lib/gm/notepad/line_evaluator.rb