Class: Snipe::Command

Inherits:
CLAide::Command
  • Object
show all
Defined in:
lib/snipe/commands/command.rb

Direct Known Subclasses

InitCommand

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(argv) ⇒ Command

Returns a new instance of Command.



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/snipe/commands/command.rb', line 23

def initialize(argv)
  assert_configured!

  config = Config.new
  config.load

  @api_key = config.api_key
  @domain = config.domain
  @from = argv.option("f") || argv.option("from") || config.from
  @to =  argv.option("t") || argv.option("to") || argv.option("target")
  @message = argv.option("message")
  @subject = argv.option("subject") || create_subject(@message)

  super
end

Class Method Details

.optionsObject



14
15
16
17
18
19
20
21
# File 'lib/snipe/commands/command.rb', line 14

def self.options
  [
    ['--target|--to', 'The address to send the email to'],
    ['--message', 'A message to send'],
    ['[--subject]', 'Derived from the message by default'],
    ['[--from]', 'Override the default "from" address'],
  ].concat(super)
end

.report_error(exception) ⇒ Object



64
65
66
67
68
69
70
# File 'lib/snipe/commands/command.rb', line 64

def self.report_error(exception)
  if exception.instance_of?(SnipeException)
    puts exception.message
    exit 1
  end
  fail exception
end

Instance Method Details

#assert_configured!Object



49
50
51
# File 'lib/snipe/commands/command.rb', line 49

def assert_configured!
  fail SnipeException, "Run `snipe init` first!" unless Config.exists?
end

#create_subject(message) ⇒ Object



59
60
61
62
# File 'lib/snipe/commands/command.rb', line 59

def create_subject(message)
  return nil unless message
  message.split(" ").take(8).join(" ")
end

#runObject



39
40
41
42
43
44
45
46
47
# File 'lib/snipe/commands/command.rb', line 39

def run
  client = Mailgun::Client.new(@api_key)
  params = { from: @from, to: @to, subject: @subject, text: @message }
  response = client.send_message(@domain, params)

  output_message = response.code == 200 ? "Email Sent" : "Error"
  body = JSON.parse(response.body)
  puts "[#{response.code}] #{output_message} : #{body["message"]}"
end

#validate!Object



53
54
55
56
57
# File 'lib/snipe/commands/command.rb', line 53

def validate!
  help! "You must provide a valid `--from`" unless Validate.email!(@from)
  help! "You must provide a valid `--target`" unless Validate.email!(@to)
  help! "You must provide a `--message`" unless @message
end