Class: Daily::Txt::Config

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

Defined Under Namespace

Classes: Invalid, NotFound, ParseError

Constant Summary collapse

DEFAULT_CONFIG_PATH =
"#{Dir.home}/.daily_txt_config.json"
DEFAULT_ROOT_DIR =
"daily_txt"
REQUIRED_KEYS =
[
  "home",
  "editor",
  "color"
]

Class Method Summary collapse

Class Method Details

.create_defaultObject



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/daily/txt/config.rb', line 34

def create_default
  editors = Daily::Txt::System.find_editor
  if editors.empty?
    abort('No editor found')
  end

  selected_editor = editors.size == 1 ?  editors.first : nil
  unless selected_editor
    selected_editor = select_from_candidates(
      "> Which editor do you use? : ", editors)
  end

  config = {
    "home" => File.join(Dir.home, DEFAULT_ROOT_DIR),
    "editor" => selected_editor,
    "color" => true
  }
  File.write(DEFAULT_CONFIG_PATH,
    JSON.pretty_generate(config))
  self.load(DEFAULT_CONFIG_PATH)
end

.load(path) ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/daily/txt/config.rb', line 56

def load(path)
  path ||= DEFAULT_CONFIG_PATH

  unless File.readable?(path)
    raise NotFound, "file not found: #{path}"
  end

  begin
    config = JSON.parse(IO.read(path))
  rescue JSON::ParserError => e
    raise ParseError, "cannot parse: #{path}"
  end
  validate(config)
  config
end

.select_from_candidates(label, candidates) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/daily/txt/config.rb', line 20

def select_from_candidates(label, candidates)
  index = 1
  candidates.each do |candidate|
    puts "[#{index}] #{candidate}"
    index = index + 1
  end
  input = Daily::Txt::System.wait_input(label)
  selected_index = input.to_i - 1
  if selected_index >= 0 && candidates[selected_index]
    return candidates[selected_index]
  end
  abort("invalid selection: #{input}")
end

.validate(config) ⇒ Object



72
73
74
75
76
77
78
79
# File 'lib/daily/txt/config.rb', line 72

def validate(config)
  REQUIRED_KEYS.each do |key|
    unless config.has_key?(key)
      raise Invalid, "config has not required key: #{key}"
    end
  end
  true;
end