Class: RubyCms::Preference

Inherits:
ApplicationRecord
  • Object
show all
Defined in:
app/models/ruby_cms/preference.rb

Overview

Stores configuration preferences for the CMS admin interface. Preferences are key-value pairs with optional type casting.

Constant Summary collapse

VALUE_TYPES =
%w[string integer boolean json].freeze

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.all_as_hashObject



28
29
30
# File 'app/models/ruby_cms/preference.rb', line 28

def self.all_as_hash
  all.to_h {|pref| [pref.key.to_sym, pref.typed_value] }
end

.by_categoryObject



46
47
48
# File 'app/models/ruby_cms/preference.rb', line 46

def self.by_category
  all.group_by(&:category)
end

.defaultsObject



50
51
52
# File 'app/models/ruby_cms/preference.rb', line 50

def self.defaults
  RubyCms::SettingsRegistry.defaults_hash
end

.ensure_defaults!Object



32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'app/models/ruby_cms/preference.rb', line 32

def self.ensure_defaults!
  defaults.each do |key, config|
    next if exists?(key: key.to_s)

    create!(
      key: key.to_s,
      value: serialize_seed_value(config[:value], config[:type]),
      value_type: config[:type],
      description: config[:description],
      category: config[:category] || "general"
    )
  end
end

.get(key, default: nil) ⇒ Object



14
15
16
17
18
19
# File 'app/models/ruby_cms/preference.rb', line 14

def self.get(key, default: nil)
  pref = find_by(key: key.to_s)
  return default if pref.nil?

  pref.typed_value
end

.set(key, value) ⇒ Object



21
22
23
24
25
26
# File 'app/models/ruby_cms/preference.rb', line 21

def self.set(key, value)
  pref = find_or_initialize_by(key: key.to_s)
  pref.assign_value(value)
  pref.save!
  pref.typed_value
end

Instance Method Details

#assign_value(new_value) ⇒ Object



65
66
67
68
# File 'app/models/ruby_cms/preference.rb', line 65

def assign_value(new_value)
  self.value_type ||= detect_type(new_value)
  self.value = serialize_value(new_value)
end

#typed_valueObject



54
55
56
57
58
59
60
61
62
63
# File 'app/models/ruby_cms/preference.rb', line 54

def typed_value
  case value_type
  when "integer" then value.to_i
  when "boolean" then boolean_cast(value)
  when "json" then parse_json_value(value)
  else value
  end
rescue JSON::ParserError, TypeError
  value.to_s
end