Class: GlobalSetting

Inherits:
ActiveRecord::Base
  • Object
show all
Defined in:
app/models/global_setting.rb

Overview

A model for storing key-value pairs, intended for global server configuration settings, with the ability to gracefully handle multiple data types.

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.get(key) ⇒ Object

Returns the stored value in the record associated with the key. Will attempt to access cache before the database to minimize database load.

  • key - A string containing the name associated with the setting.


60
61
62
63
64
65
# File 'app/models/global_setting.rb', line 60

def get(key)
  Rails.cache.fetch "globalsetting/#{key}" do
    setting = find_by(key: key)
    setting.nil? ? nil : setting.value
  end
end

.set(key, value) ⇒ Object

Updates or creates a new record for the given key, with the given value. The datatype will be determined automatically. Returns the GlobalSetting object that was created. Raises ActiveRecord::RecordInvalid if key is invalid

  • key - A string containing the name associated with the setting.

  • value - The value to be stored.


50
51
52
53
54
55
# File 'app/models/global_setting.rb', line 50

def set(key, value)
  setting = find_or_create_by(key: key)
  setting.value = value
  setting.save!
  setting
end

.unset(key) ⇒ Object

Deletes a setting from the database, or returns false if the setting doesn't exist.

  • key - A string containing the name associated with the setting.


70
71
72
73
# File 'app/models/global_setting.rb', line 70

def unset(key)
  setting = find_by(key: key)
  setting.nil? ? false : setting.destroy
end

Instance Method Details

#valueObject

Accessor for the setting's stored data. Uses #datatype to determine the correct model attribute.


13
14
15
# File 'app/models/global_setting.rb', line 13

def value
  send(datatype.to_sym)
end

#value=(value) ⇒ Object

Stores a value in the appropriate model attribute based on the class of the value object (and updates the datatype), but does not commit the change to the database. Returns the value as it will be committed–i.e. stringified, intified, etc.

  • value - The value to be stored.


22
23
24
25
26
# File 'app/models/global_setting.rb', line 22

def value=(value)
  self.datatype = datatype_from_object(value)
  send("#{datatype}=".to_sym, value)
  self.value
end