Class: UppityRobot::CLI::Commands::Monitors::Update

Inherits:
Dry::CLI::Command
  • Object
show all
Defined in:
lib/uppityrobot/cli/commands/monitors/update.rb

Overview

UppityRobot::CLI::Commands::Monitors::Update update monitors

Instance Method Summary collapse

Instance Method Details

#call(format:, data:) ⇒ Object

rubocop:disable Metrics/AbcSize



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/uppityrobot/cli/commands/monitors/update.rb', line 21

def call(format:, data:, **)
  check_format(format)
  data = parse_data(format, data)
  unless data.is_a? Array
    abort(
      {stat: "fail", error: "Data must be an array: #{data.inspect}"}.to_json
    )
  end

  updated = {stat: "ok", total: 0, updated: 0, monitors: [], errors: []}
  data.each do |d|
    original = d.dup # UptimeRobot::Client modifies `d`, avoid this for errors
    updated[:total] += 1
    updated[:monitors] << UppityRobot::Client.new(:editMonitor, d).execute
    updated[:updated] += 1
  rescue UptimeRobot::Error => e
    updated[:errors] << "#{e.message} for: #{original.inspect}"
  end

  puts updated.to_json
rescue CSV::MalformedCSVError, JSON::ParserError => e
  puts JSON.generate({stat: "fail", error: "Invalid input: #{e.message}"})
end

#check_format(format) ⇒ Object

rubocop:enable Metrics/AbcSize



46
47
48
49
50
51
# File 'lib/uppityrobot/cli/commands/monitors/update.rb', line 46

def check_format(format)
  return if %w[csv json].include? format

  abort({stat: "fail",
         error: "Format not recognized, must be one of: [csv, json]"}.to_json)
end

#parse_data(format, data) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/uppityrobot/cli/commands/monitors/update.rb', line 53

def parse_data(format, data)
  if format == "json" && File.file?(data)
    JSON.parse(File.read(data))
  elsif format == "json"
    JSON.parse(data)
  elsif format == "csv" && File.file?(data)
    rows = []
    CSV.foreach(data, headers: true, header_converters: :symbol) do |row|
      rows << row.to_hash
    end
    rows
  else
    abort({stat: "fail", error: "Error parsing data: #{format}, #{data.inspect}"}.to_json)
  end
end