Class: Jets::Api::Config

Inherits:
Object
  • Object
show all
Extended by:
Memoist
Includes:
Singleton
Defined in:
lib/jets/api/config.rb

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Config

Returns a new instance of Config.



8
9
10
11
# File 'lib/jets/api/config.rb', line 8

def initialize(options = {})
  @options = options
  @config_path = "#{ENV["HOME"]}/.jets/config.yml"
end

Instance Method Details

#api_keyObject



13
14
15
# File 'lib/jets/api/config.rb', line 13

def api_key
  ENV["JETS_API_KEY"] || data["api_key"] || data["key"] # keep key for backwards compatibility
end

#api_key?Boolean

Returns:

  • (Boolean)


17
18
19
# File 'lib/jets/api/config.rb', line 17

def api_key?
  !!api_key
end

#clear_api_keyObject



21
22
23
24
# File 'lib/jets/api/config.rb', line 21

def clear_api_key
  FileUtils.rm_f(@config_path)
  puts "Removed #{@config_path.sub(ENV["HOME"], "~")}"
end

#dataObject



26
27
28
# File 'lib/jets/api/config.rb', line 26

def data
  @data ||= load
end

#loadObject

Ensure a Hash is returned



31
32
33
34
35
36
37
38
39
40
41
# File 'lib/jets/api/config.rb', line 31

def load
  return {} unless File.exist?(@config_path)

  data = YAML.load_file(@config_path)
  if data.is_a?(Hash)
    data
  else
    puts "WARN: #{@config_path} is not in the correct format. Loading an empty hash.".color(:yellow)
    {}
  end
end

#pretty_path(path) ⇒ Object



69
70
71
# File 'lib/jets/api/config.rb', line 69

def pretty_path(path)
  path.sub(ENV["HOME"], "~")
end

#promptObject



43
44
45
46
47
48
49
50
# File 'lib/jets/api/config.rb', line 43

def prompt
  puts <<~EOL
    You are about to configure your #{pretty_path(@config_path)}
    You can get an api key from www.rubyonjets.com
  EOL
  print "Please provide your api key: "
  $stdin.gets.strip
end

#update_api_key(api_key = nil) ⇒ Object

interface method: do not remove



53
54
55
56
57
58
59
# File 'lib/jets/api/config.rb', line 53

def update_api_key(api_key = nil)
  api_key ||= prompt
  write(
    key: api_key,     # legacy jets 5 and below
    api_key: api_key  # legacy jets 6 and above
  ) # specify keys to allow
end

#write(values = {}) ⇒ Object



61
62
63
64
65
66
67
# File 'lib/jets/api/config.rb', line 61

def write(values = {})
  data = load
  data.merge!(values.deep_stringify_keys)
  FileUtils.mkdir_p(File.dirname(@config_path))
  IO.write(@config_path, YAML.dump(data))
  puts "Updated #{pretty_path(@config_path)}"
end