Class: Rtprov::Router

Inherits:
Object
  • Object
show all
Defined in:
lib/rtprov/router.rb

Constant Summary collapse

ATTRIBUTES =
%w(host user password administrator_password anonymous_password variables).map(&:freeze).freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, attributes) ⇒ Router

Returns a new instance of Router.



67
68
69
70
71
72
73
74
# File 'lib/rtprov/router.rb', line 67

def initialize(name, attributes)
  @name = name

  attributes.each do |k, v|
    ATTRIBUTES.include?(k) || raise("Unknown attribute found `#{k}`")
    instance_variable_set "@#{k}", v
  end
end

Class Method Details

.decrypt(name) ⇒ Object



53
54
55
# File 'lib/rtprov/router.rb', line 53

def self.decrypt(name)
  Encryption.decrypt(File.read("routers/#{name}.yml.enc"))
end

.edit(name) ⇒ Object



10
11
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
# File 'lib/rtprov/router.rb', line 10

def self.edit(name)
  encrypted_file = "routers/#{name}.yml.enc"
  decrypted = if File.exist?(encrypted_file)
    Encryption.decrypt(File.read(encrypted_file))
  else
    <<~YAML
      host: 127.0.0.1
      user: admin
      password: opensesame
      administrator_password: opensesame
      anonymous_password: anonymous_password
      variables: {}
    YAML
  end

  Dir.mktmpdir do |dir|
    temp = "#{dir}/#{name}.yml"
    File.write(temp, decrypted)

    if system("#{editor} #{temp.shellescape}", out: $stdout, err: $stderr)
      encrypted = Encryption.encrypt(File.read(temp))
      File.write(encrypted_file, encrypted)
      warn "Saved to #{encrypted_file}"
    else
      warn "Not saved"
    end
  end
end

.editorObject



39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/rtprov/router.rb', line 39

def self.editor
  return ENV["RTPROV_EDITOR"] if ENV["RTPROV_EDITOR"]

  # rubocop: disable Lint/HandleExceptions
  begin
    o, _e, s = Open3.capture3("git config core.editor")
    return o.strip if s.success?
  rescue Errno::ENOENT
  end
  # rubocop: enable Lint/HandleExceptions

  ENV["EDITOR"]
end

.load(name) ⇒ Object



63
64
65
# File 'lib/rtprov/router.rb', line 63

def self.load(name)
  new(name, YAML.safe_load(decrypt(name)))
end

.namesObject



57
58
59
60
61
# File 'lib/rtprov/router.rb', line 57

def self.names
  Dir["routers/*.yml.enc"].map {|path|
    File.basename(path).gsub(/\.yml\.enc\z/, "")
  }.sort
end