Class: TheDude::Command

Inherits:
Object
  • Object
show all
Defined in:
lib/the_dude/command.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(expression, answer = nil, &block_answer) ⇒ TheDude::Command

Initializes a new command.

An instance is created to hold the details of the command and the command is registered in TheDude.commands using the provided key. The answer can be a string, proc or block. If both a string/proc and block are passed, the block will take precedence.

Examples:


command = TheDude::Command.new 'hello', 'hello'
TheDude.commands['hello'] == command # true

TheDude::Command.new 'hello' do
  puts 'hello'
  puts 'how are you?'
end

Parameters:

  • expression (String | Regexp)

    the question to ask

  • answer (String | Proc) (defaults to: nil)

    the answer to the question



30
31
32
33
34
35
# File 'lib/the_dude/command.rb', line 30

def initialize expression, answer=nil, &block_answer
  @expression = Expression.new(expression)
  @answer = block_answer || answer

  TheDude.register_command self
end

Instance Attribute Details

#answerObject

String | Proc | Block

The answer for this command



7
8
9
# File 'lib/the_dude/command.rb', line 7

def answer
  @answer
end

#expressionObject (readonly)

TheDude::Expression

The expression for this command



4
5
6
# File 'lib/the_dude/command.rb', line 4

def expression
  @expression
end

Instance Method Details

#ask(*args) ⇒ Object

Asks the question with the specified arguments. If the answer is a string it is returned. If it is a proc or block it is evaluated with the passed parameters.



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/the_dude/command.rb', line 40

def ask *args
  begin
    if answer.kind_of?(Proc)
      TheDude::Dsl.new.instance_exec(*args, &answer)
    else
      answer
    end
  rescue SystemExit
    exit
  rescue Interrupt
    TheDude.say 'Fine, i\'ll leave it then'
  rescue Exception => e
    TheDude.complain "Man, what are you doing? Look what you just did\n
    #{e.class}
    #{e.message}
    #{e.backtrace}
    At least you didn't pee on my rug I guess
    "
  end
end