lib/games_dice/parser.rb in games_dice-0.2.2 vs lib/games_dice/parser.rb in games_dice-0.2.3
- old
+ new
@@ -1,8 +1,13 @@
require 'parslet'
-# converts string dice descriptions to data usable for the GamesDice::Dice constructor
+# 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.
+#
+
class GamesDice::Parser < Parslet::Parser
# Parslet rules that define the dice string grammar.
rule(:integer) { match('[0-9]').repeat(1) }
rule(:plus_minus_integer) { ( match('[+-]') >> integer ) | integer }
@@ -60,9 +65,13 @@
rule(:add_constant) { operator >> integer.as(:constant) >> space? }
rule(:dice_expression) { add_bunch | add_constant }
rule(:expressions) { dice_expression.repeat.as(:bunches) }
root :expressions
+ # Parses a string description in the dice mini-language, and returns data for feeding into
+ # GamesDice::Dice constructore.
+ # @param [String] dice_description Text to parse e.g. '1d6'
+ # @return [Hash] Analysis of dice_description
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 dice_description =~ /\A[+-]/
dice_expressions = super( dice_description )