Class: Pairity

Inherits:
Object
  • Object
show all
Defined in:
lib/pairity.rb,
lib/pairity/version.rb

Defined Under Namespace

Classes: KeyNotConfigured

Constant Summary collapse

VERSION =
"0.0.1"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name) ⇒ Pairity

Returns a new instance of Pairity.



54
55
56
# File 'lib/pairity.rb', line 54

def initialize(name)
  self.name = name.upcase
end

Instance Attribute Details

#nameObject

Returns the value of attribute name.



52
53
54
# File 'lib/pairity.rb', line 52

def name
  @name
end

Class Method Details

.homeObject



16
17
18
# File 'lib/pairity.rb', line 16

def self.home
  ENV['HOME'] || '/tmp'
end

.rootObject



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

def self.root
  @root ||= File.join(home, '.pairity')
end

.root=(path) ⇒ Object



24
25
26
# File 'lib/pairity.rb', line 24

def self.root=(path)
  @root = path
end

.with_key_paths(*key_names, &blk) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
# File 'lib/pairity.rb', line 28

def self.with_key_paths(*key_names, &blk)
  keys = key_names.map { |name| new(name) }

  paths = keys.map(&:path)

  result = blk.call *paths

  keys.map(&:unlink_temp_file)

  result
end

.with_keys(*key_names, &blk) ⇒ Object



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

def self.with_keys(*key_names, &blk)
  keys = key_names.map { |name| new(name) }

  contents = keys.map(&:content)

  result = blk.call *contents

  keys.map(&:unlink_temp_file)

  result
end

Instance Method Details

#contentObject



81
82
83
# File 'lib/pairity.rb', line 81

def content
  File.read path
end

#default_pathObject



98
99
100
# File 'lib/pairity.rb', line 98

def default_path
  File.join(self.class.root, "#{friendly_name}.key")
end

#envObject



62
63
64
# File 'lib/pairity.rb', line 62

def env
  ENV[name]
end

#friendly_nameObject



58
59
60
# File 'lib/pairity.rb', line 58

def friendly_name
  name.downcase.gsub('_', '-')
end

#pathObject



69
70
71
72
73
74
75
76
77
78
79
# File 'lib/pairity.rb', line 69

def path
  if File.exist?(default_path)
    default_path
  elsif path_env
    path_env
  elsif env
    temp_path
  else
    raise KeyNotConfigured, name
  end
end

#path_envObject



65
66
67
# File 'lib/pairity.rb', line 65

def path_env
  ENV["#{name}_PATH"]
end

#temp_fileObject



89
90
91
92
93
94
95
96
# File 'lib/pairity.rb', line 89

def temp_file
  return @temp_file if @temp_file && File.exist?(@temp_file)

  file = Tempfile.new 'temp-key'
  file.write env
  file.close
  @temp_path = file
end

#temp_pathObject



85
86
87
# File 'lib/pairity.rb', line 85

def temp_path
  temp_file.path
end


102
103
104
105
106
# File 'lib/pairity.rb', line 102

def unlink_temp_file
  if path_env.nil? && env
    temp_file.unlink
  end
end