Class: CarbonMU::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/carbonmu/parser.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeParser

Returns a new instance of Parser.



12
13
14
15
# File 'lib/carbonmu/parser.rb', line 12

def initialize
  @syntaxes = {}
  Command.command_classes.each { |klass| register_command_class(klass) }
end

Instance Attribute Details

#syntaxesObject (readonly)

Returns the value of attribute syntaxes.



10
11
12
# File 'lib/carbonmu/parser.rb', line 10

def syntaxes
  @syntaxes
end

Instance Method Details

#parse(input) ⇒ Object



24
25
26
27
28
29
30
31
32
# File 'lib/carbonmu/parser.rb', line 24

def parse(input)
  syntax_match_data = {}
  syntax_and_class = @syntaxes.detect { |syntax, klass| syntax_match_data = syntax.match(input) }

  command_class = syntax_and_class.nil? ? UnknownCommand : syntax_and_class[1]
  syntax_match_data ||= {} # if no syntaxes matched

  [command_class, syntax_match_data.to_hash]
end

#parse_and_execute(enacting_connection, input) ⇒ Object



17
18
19
20
21
22
# File 'lib/carbonmu/parser.rb', line 17

def parse_and_execute(enacting_connection, input)
  command_class, params = parse(input)

  context = CommandContext.new(enacting_connection: enacting_connection, raw_command: input, params: params)
  command_class.new(context).execute
end

#register_command_class(klass) ⇒ Object



34
35
36
# File 'lib/carbonmu/parser.rb', line 34

def register_command_class(klass)
  klass.syntaxes.each { |syntax| register_syntax(syntax, klass) }
end

#register_syntax(syntax, klass) ⇒ Object



38
39
40
# File 'lib/carbonmu/parser.rb', line 38

def register_syntax(syntax, klass)
  @syntaxes[syntax] = klass
end