Class: GamesDice::Parser

Inherits:
Parslet::Parser
  • Object
show all
Defined in:
lib/games_dice/parser.rb

Overview

Based on the parslet gem, this class defines the dice mini-language used by GamesDice.create

An instance of this class is a parser for the language. There are no user-definable instance variables.

Instance Method Summary collapse

Instance Method Details

#parse(dice_description) ⇒ Hash

Parses a string description in the dice mini-language, and returns data for feeding into GamesDice::Dice constructor.

Parameters:

  • dice_description (String)

    Text to parse e.g. '1d6'

Returns:

  • (Hash)

    Analysis of dice_description



80
81
82
83
84
85
86
87
88
89
# File 'lib/games_dice/parser.rb', line 80

def parse(dice_description)
  dice_description = dice_description.to_s.strip
  # Force first item to start '+' for simpler parse rules
  dice_description = "+#{dice_description}" unless /\A[+-]/.match?(dice_description)
  dice_expressions = super
  {
    bunches: ParseTreeProcessor.collect_bunches(dice_expressions),
    offset: ParseTreeProcessor.collect_offset(dice_expressions)
  }
end