Class: PagecordCLI::Config

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

Defined Under Namespace

Classes: Error

Constant Summary collapse

DEFAULT_PATH =
File.expand_path("~/.pagecord.yml")
DEFAULT_BASE_URL =
"https://api.pagecord.com"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path = DEFAULT_PATH) ⇒ Config

Returns a new instance of Config.



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

def initialize(path = DEFAULT_PATH)
  @path = path
end

Instance Attribute Details

#pathObject (readonly)

Returns the value of attribute path.



15
16
17
# File 'lib/pagecord_cli/config.rb', line 15

def path
  @path
end

Class Method Details

.api_or_local_host?(host) ⇒ Boolean

Returns:

  • (Boolean)


72
73
74
# File 'lib/pagecord_cli/config.rb', line 72

def self.api_or_local_host?(host)
  host.start_with?("api.") || %w[localhost 127.0.0.1 ::1].include?(host)
end

.normalize_base_url(url) ⇒ Object



21
22
23
24
25
26
27
# File 'lib/pagecord_cli/config.rb', line 21

def self.normalize_base_url(url)
  uri = URI(url.match?(%r{\Ahttps?://}) ? url : "https://#{url}")
  return uri.to_s.delete_suffix("/") if api_or_local_host?(uri.host)

  uri.host = "api.#{uri.host}"
  uri.to_s.delete_suffix("/")
end

Instance Method Details

#blog(name) ⇒ Object



33
34
35
# File 'lib/pagecord_cli/config.rb', line 33

def blog(name)
  blogs[name]
end

#blogsObject



29
30
31
# File 'lib/pagecord_cli/config.rb', line 29

def blogs
  data.fetch("blogs", {})
end

#dataObject



62
63
64
65
66
67
68
# File 'lib/pagecord_cli/config.rb', line 62

def data
  return { "blogs" => {} } unless File.exist?(path)

  YAML.safe_load_file(path, permitted_classes: [ Time, Date ], aliases: false) || { "blogs" => {} }
rescue Psych::Exception => e
  raise Error, "Could not read #{path}: #{e.message}"
end

#delete_blog(name) ⇒ Object



47
48
49
50
51
# File 'lib/pagecord_cli/config.rb', line 47

def delete_blog(name)
  new_data = data
  new_data.fetch("blogs", {}).delete(name)
  write(new_data)
end

#resolve_blog(name = nil) ⇒ Object



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

def resolve_blog(name = nil)
  return name if name && blog(name)
  return name if name

  return blogs.keys.first if blogs.size == 1

  nil
end

#save_blog(name, api_key:, base_url: DEFAULT_BASE_URL) ⇒ Object



37
38
39
40
41
42
43
44
45
# File 'lib/pagecord_cli/config.rb', line 37

def save_blog(name, api_key:, base_url: DEFAULT_BASE_URL)
  new_data = data
  new_data["blogs"] ||= {}
  new_data["blogs"][name] = {
    "api_key" => api_key,
    "base_url" => base_url
  }
  write(new_data)
end