Class: SystemConfig
- Inherits:
-
BarkestCore::DbTable
- Object
- ActiveRecord::Base
- BarkestCore::DbTable
- SystemConfig
- Defined in:
- app/models/system_config.rb
Overview
Defines a mechanism to store and retrieve configurations using the core database.
The get
and set
methods allow values to be stored in an encrypted fashion as well.
The encryption will use the encrypted_config_key
value or the secret_key_base
value from secrets.yml
. Ideally, use encrypted_config_key
to allow secret_key_base
to change if necessary.
Class Method Summary collapse
-
.get(key_name) ⇒ Object
Gets a value from the database.
-
.set(key_name, value, encrypt = false) ⇒ Object
Stores a value to the database.
Instance Method Summary collapse
-
#value ⇒ Object
Gets the value loading it from a YAML string.
-
#value=(new_value) ⇒ Object
Sets the value storing it as a YAML string.
Class Method Details
.get(key_name) ⇒ Object
Gets a value from the database.
If the value was stored encrypted, it will be decrypted before being returned.
As a feature during testing config/key_name.yml
will be used if it exists and the database value is missing.
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
# File 'app/models/system_config.rb', line 43 def self.get(key_name) begin record = where(key: key_name.to_s.downcase).first if record value = record.value if value.is_a?(Hash) && value.keys.include?(:encrypted_value) value = value[:encrypted_value] unless value.nil? || value == '' value = YAML.load(crypto_cipher.decrypt(value)) rescue nil end end elsif Rails.env.test? yml_file = "#{BarkestCore.app_root}/config/#{key_name}.yml" value = File.exist?(yml_file) ? YAML.load_file(yml_file) : nil else value = nil end value rescue nil # if 'system_configs' table has not been created, return nil. end end |
.set(key_name, value, encrypt = false) ⇒ Object
Stores a value to the database.
All values are converted into YAML strings before storage.
If encrypt
is set to true, then the value will be encrypted before being stored.
74 75 76 77 78 79 80 81 82 83 |
# File 'app/models/system_config.rb', line 74 def self.set(key_name, value, encrypt = false) key_name = key_name.to_s.downcase if encrypt value = crypto_cipher.encrypt(value.to_yaml) unless value.nil? || value == '' value = { encrypted_value: value } end record = find_or_initialize_by(key: key_name) record.value = value record.save end |
Instance Method Details
#value ⇒ Object
Gets the value loading it from a YAML string.
29 30 31 32 33 |
# File 'app/models/system_config.rb', line 29 def value val = read_attribute(:value).to_s return nil if val.empty? YAML.load val end |
#value=(new_value) ⇒ Object
Sets the value storing it as a YAML string.
22 23 24 25 |
# File 'app/models/system_config.rb', line 22 def value=(new_value) val = new_value.nil? ? nil : new_value.to_yaml write_attribute :value, val end |