Class: Britebox::Config

Inherits:
Object
  • Object
show all
Includes:
ActiveModel::Validations, Singleton
Defined in:
lib/britebox/config.rb

Constant Summary collapse

OPTIONS =
[:threads, :api_key, :watch_dir, :out_dir, :port, :ui_enabled, :simulate]
MAX_THREADS =
10
DEFAULT_OPTIONS =
{
  threads: 10,
  port: 7000
}
CONFIG_PATH =
'~/.britebox.json'

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeConfig

Returns a new instance of Config.



27
28
29
30
# File 'lib/britebox/config.rb', line 27

def initialize
  # load config file
  init_defaults
end

Class Method Details

.method_missing(method, *args) ⇒ Object



32
33
34
35
36
37
38
# File 'lib/britebox/config.rb', line 32

def self.method_missing(method, *args)
  if self.instance.respond_to? method
    self.instance.send(method, *args)
  else
    super
  end
end

.respond_to?(method) ⇒ Boolean

Returns:

  • (Boolean)


40
41
42
43
44
45
46
# File 'lib/britebox/config.rb', line 40

def self.respond_to?(method)
  if self.instance.respond_to? method
    true
  else
    super
  end
end

Instance Method Details

#attributesObject



76
77
78
# File 'lib/britebox/config.rb', line 76

def attributes
  values
end

#loadObject



48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/britebox/config.rb', line 48

def load
  data = read_config

  if data && data['config']
    data['config'].each do |k, v|
      self.send("#{k}=", v) if self.respond_to?(k)
    end
    true
  else
    false
  end
end

#read_configObject



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

def read_config
  path = File.expand_path(CONFIG_PATH)
  if File.exists? path
    JSON.parse File.read path rescue nil
  end
end

#saveObject



96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/britebox/config.rb', line 96

def save
  path = File.expand_path(CONFIG_PATH)

  data = read_config
  data ||= {}
  data['config'] = attributes

  begin
    File.open(path, 'w+') do |file|
      file.write JSON.pretty_generate data
    end
    true
  rescue Exception => ex
    puts "Can't save config: #{ex.message}"
    false
  end
end

#update(new_values) ⇒ Object



80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/britebox/config.rb', line 80

def update(new_values)
  old_values = self.attributes

  new_values.each do |k, v|
    self.send("#{k}=", v)
  end
  if self.valid?
    save
  else
    old_values.each do |k, v|
      self.send("#{k}=", v)
    end
    false
  end
end

#valuesObject



68
69
70
71
72
73
74
# File 'lib/britebox/config.rb', line 68

def values
  data = {}
  OPTIONS.each do |k|
    data[k] = self.send(k)
  end
  data
end