Class: PocketVault

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

Constant Summary collapse

VERSION =
"0.1.0"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url:, token:, environment: "production", refresh_interval: nil) ⇒ PocketVault

Returns a new instance of PocketVault.



10
11
12
13
14
15
16
17
18
# File 'lib/pocketvault.rb', line 10

def initialize(url:, token:, environment: "production", refresh_interval: nil)
  @url = url.chomp("/")
  @token = token
  @environment = environment
  @cache = {}
  @loaded_at = nil
  @refresh_interval = refresh_interval
  @mutex = Mutex.new
end

Instance Attribute Details

#environmentObject (readonly)

Returns the value of attribute environment.



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

def environment
  @environment
end

#urlObject (readonly)

Returns the value of attribute url.



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

def url
  @url
end

Instance Method Details

#allObject



25
26
27
28
# File 'lib/pocketvault.rb', line 25

def all
  load! if stale?
  @cache.dup
end

#get(key) ⇒ Object



20
21
22
23
# File 'lib/pocketvault.rb', line 20

def get(key)
  load! if stale?
  @cache[key]
end

#load!Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/pocketvault.rb', line 30

def load!
  @mutex.synchronize do
    uri = URI("#{@url}/api/v1/secrets?environment=#{@environment}")
    req = Net::HTTP::Get.new(uri)
    req["Authorization"] = "Bearer #{@token}"

    res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http|
      http.request(req)
    end

    raise "PocketVault error: #{res.code} #{res.body}" unless res.is_a?(Net::HTTPSuccess)

    secrets = JSON.parse(res.body)
    @cache = secrets.each_with_object({}) { |s, h| h[s["key"]] = s["value"] }
    @loaded_at = Time.now
  end
  self
end

#to_envObject



49
50
51
# File 'lib/pocketvault.rb', line 49

def to_env
  all.each { |k, v| ENV[k] = v }
end