class BCDice::Preprocessor

入力文字列に対して前処理を行う

@example

Preprocessor.process(
  "1d6+4D+(3*4) 切り取られる部分",
  game_system
) #=> "1d6+4D6+7"

Public Class Methods

new(text, game_system) click to toggle source

@param text [String] @param game_system [Base]

# File lib/bcdice/preprocessor.rb, line 20
def initialize(text, game_system)
  @text = text
  @game_system = game_system
end
process(text, game_system) click to toggle source

@param (see initialize) @return [String]

# File lib/bcdice/preprocessor.rb, line 14
def self.process(text, game_system)
  Preprocessor.new(text, game_system).process()
end

Public Instance Methods

process() click to toggle source

@return [String]

# File lib/bcdice/preprocessor.rb, line 26
def process
  trim_after_whitespace()
  replace_parentheses()

  @text = @game_system.change_text(@text)

  replace_implicit_d()

  return @text
end

Private Instance Methods

replace_implicit_d() click to toggle source

nDをゲームシステムに応じて置き換える

# File lib/bcdice/preprocessor.rb, line 56
def replace_implicit_d
  @text = @text.gsub(/(\d+)D([^\w]|$)/i) do
    times = Regexp.last_match(1)
    sides = @game_system.sides_implicit_d
    trailer = Regexp.last_match(2)

    "#{times}D#{sides}#{trailer}"
  end
end
replace_parentheses() click to toggle source

カッコ書きの数式を事前計算する

# File lib/bcdice/preprocessor.rb, line 45
def replace_parentheses
  loop do
    prev = @text
    @text = @text.gsub(%r{\([\d/+*\-CURF]+\)}) do |expr|
      Arithmetic.eval(expr, @game_system.round_type) || expr
    end
    break if prev == @text
  end
end
trim_after_whitespace() click to toggle source

空白より前だけを取る

# File lib/bcdice/preprocessor.rb, line 40
def trim_after_whitespace()
  @text = @text.strip.split(/\s/, 2).first
end