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,
  :logging_enabled, :log_file
]
MAX_THREADS =
10
DEFAULT_OPTIONS =
{
  threads: 10,
  port: 7000,
  logging_enabled: false,
  log_file: '~/britebox.log'
}
CONFIG_PATH =
'~/.britebox.json'

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeConfig

Returns a new instance of Config.



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

def initialize
  # load config file
  init_defaults
end

Class Method Details

.method_missing(method, *args) ⇒ Object



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

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)


45
46
47
48
49
50
51
# File 'lib/britebox/config.rb', line 45

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

Instance Method Details

#attributesObject



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

def attributes
  values
end

#loadObject



53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/britebox/config.rb', line 53

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



66
67
68
69
70
71
# File 'lib/britebox/config.rb', line 66

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

#saveObject



101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/britebox/config.rb', line 101

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



85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/britebox/config.rb', line 85

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



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

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