Class: Kennel::Importer

Inherits:
Object
  • Object
show all
Defined in:
lib/kennel/importer.rb

Constant Summary collapse

TITLES =
[:name, :title].freeze
SORT_ORDER =
[*TITLES, :id, :kennel_id, :type, :tags, :query, :message, :description, :template_variables].freeze

Instance Method Summary collapse

Constructor Details

#initialize(api) ⇒ Importer

Returns a new instance of Importer.



8
9
10
# File 'lib/kennel/importer.rb', line 8

def initialize(api)
  @api = api
end

Instance Method Details

#import(resource, id) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/kennel/importer.rb', line 12

def import(resource, id)
  if ["screen", "dash"].include?(resource)
    raise ArgumentError, "resource 'screen' and 'dash' are deprecated, use 'dashboard'"
  end

  model =
    begin
      Kennel::Models.const_get(resource.capitalize)
    rescue NameError
      raise ArgumentError, "#{resource} is not supported"
    end

  data = @api.show(model.api_resource, id)
  id = data.fetch(:id) # keep native value
  model.normalize({}, data) # removes id
  data[:id] = id

  data[:kennel_id] = Kennel::Utils.parameterize(data.fetch(TITLES.detect { |t| data[t] }))

  if resource == "monitor"
    # flatten monitor options so they are all on the base
    data.merge!(data.delete(:options))
    data.merge!(data.delete(:thresholds) || {})
    [:notify_no_data, :notify_audit].each { |k| data.delete(k) if data[k] } # monitor uses true by default
    data = data.slice(*model.instance_methods)

    # make query use critical method if it matches
    critical = data[:critical]
    query = data[:query]
    if query && critical
      query.sub!(/([><=]) (#{Regexp.escape(critical.to_f.to_s)}|#{Regexp.escape(critical.to_i.to_s)})$/, "\\1 \#{critical}")
    end
  end

  # simplify template_variables to array of string when possible
  if vars = data[:template_variables]
    vars.map! { |v| v[:default] == "*" && v[:prefix] == v[:name] ? v[:name] : v }
  end

  pretty = pretty_print(data).lstrip.gsub("\\#", "#")
  "    \#{model.name}.new(\n      self,\n      \#{pretty}\n    )\n  RUBY\nend\n"