Module: Earthquake::Input

Included in:
Earthquake
Defined in:
lib/earthquake/input.rb

Instance Method Summary collapse

Instance Method Details

#ask(message) ⇒ Object



73
74
75
# File 'lib/earthquake/input.rb', line 73

def ask(message)
  Readline.readline(message, false)
end

#async_e(&block) ⇒ Object



77
78
79
# File 'lib/earthquake/input.rb', line 77

def async_e(&block)
  async { handle_api_error(&block) }
end

#command(pattern, options = {}, &block) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/earthquake/input.rb', line 44

def command(pattern, options = {}, &block)
  if block
    if pattern.is_a?(String) || pattern.is_a?(Symbol)
      command_name = ":#{pattern}"
      command_names << command_name
      if block.arity > 0
        pattern = %r|^#{command_name}\s+(.*)$|
      else
        pattern = %r|^#{command_name}$|
      end
    end
    command_names << ":#{options[:as]}" if options[:as]
    commands << {:pattern => pattern, :block => block}
  else
    commands.detect {|c| c[:pattern] =~ pattern}
  end
end

#command_namesObject



18
19
20
# File 'lib/earthquake/input.rb', line 18

def command_names
  @command_names ||= Set.new
end

#commandsObject



14
15
16
# File 'lib/earthquake/input.rb', line 14

def commands
  @commands ||= []
end

#completion(&block) ⇒ Object



26
27
28
# File 'lib/earthquake/input.rb', line 26

def completion(&block)
  completions << block
end

#completionsObject



22
23
24
# File 'lib/earthquake/input.rb', line 22

def completions
  @completions ||= []
end

#confirm(message, type = :y) ⇒ Object



62
63
64
65
66
67
68
69
70
71
# File 'lib/earthquake/input.rb', line 62

def confirm(message, type = :y)
  case type
  when :y
    return !(ask("#{message} [Yn] ".u) =~ /^n$/i)
  when :n
    return !!(ask("#{message} [yN] ".u) =~ /^y$/i)
  else
    raise "type must be :y or :n"
  end
end

#handle_api_error(&block) ⇒ Object



81
82
83
84
85
86
# File 'lib/earthquake/input.rb', line 81

def handle_api_error(&block)
  result = block.call
  if result["error"]
    notify "[ERROR] #{result["error"]}"
  end
end

#input(text) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/earthquake/input.rb', line 30

def input(text)
  return if text.empty?

  input_filters.each { |f| text = f.call(text) }

  if command = command(text)
    command[:block].call(command[:pattern].match(text))
  elsif !text.empty?
    puts "Command not found".c(43)
  end
rescue Exception => e
  error e
end

#input_filter(&block) ⇒ Object



10
11
12
# File 'lib/earthquake/input.rb', line 10

def input_filter(&block)
  input_filters << block
end

#input_filtersObject



6
7
8
# File 'lib/earthquake/input.rb', line 6

def input_filters
  @input_filters ||= []
end