Class: Mithril::Parsers::SimpleParser

Inherits:
Object
  • Object
show all
Defined in:
lib/mithril/parsers/simple_parser.rb

Instance Method Summary collapse

Constructor Details

#initialize(actions) ⇒ SimpleParser



7
8
9
# File 'lib/mithril/parsers/simple_parser.rb', line 7

def initialize(actions)
  @actions = actions
end

Instance Method Details

#parse_command(text) ⇒ Array

Takes a string input and separates into words, then identifies a matching action (if any) and remaining arguments. Returns both the command and the arguments array, so usage can be as follows:

Examples:

With a “say” command:

command, args = parse_command("say Greetings programs!")
  #=> command = :say, args = ["greetings", "programs"]

With no “hello” command:

command, args = parse_command("Hello world")
  #=> command = nil, args = ["hello", "world"]


27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/mithril/parsers/simple_parser.rb', line 27

def parse_command(text)
  words = wordify preprocess_input text
  
  key  = nil
  args = []
  
  while 0 < words.count
    key = words.join('_').intern
    
    return key, args if @actions.has_action? key
    
    args.unshift words.pop
  end # while
  
  return nil, args
end

#preprocess_input(text) ⇒ Object



46
47
48
49
50
# File 'lib/mithril/parsers/simple_parser.rb', line 46

def preprocess_input(text)
  text.downcase.
    gsub(/[\"?!\-',.:\(\)\[\]\;]/, ' ').
    gsub(/(\s+)/, ' ').strip
end

#wordify(text) ⇒ Object



53
54
55
# File 'lib/mithril/parsers/simple_parser.rb', line 53

def wordify(text)
  text.split(/\s+/)
end