Class: Preference
- Inherits:
-
ApplicationRecord
- Object
- ApplicationRecord
- Preference
- Defined in:
- lib/generators/ruby_cms/templates/models/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
- .all_as_hash ⇒ Object
- .by_category ⇒ Object
- .defaults ⇒ Object
- .ensure_defaults! ⇒ Object
- .get(key, default: nil) ⇒ Object
- .set(key, value) ⇒ Object
Instance Method Summary collapse
Class Method Details
.all_as_hash ⇒ Object
27 28 29 |
# File 'lib/generators/ruby_cms/templates/models/preference.rb', line 27 def self.all_as_hash all.to_h { |pref| [ pref.key.to_sym, pref.typed_value ] } end |
.by_category ⇒ Object
45 46 47 |
# File 'lib/generators/ruby_cms/templates/models/preference.rb', line 45 def self.by_category all.group_by(&:category) end |
.defaults ⇒ Object
49 50 51 |
# File 'lib/generators/ruby_cms/templates/models/preference.rb', line 49 def self.defaults RubyCms::SettingsRegistry.defaults_hash end |
.ensure_defaults! ⇒ Object
31 32 33 34 35 36 37 38 39 40 41 42 43 |
# File 'lib/generators/ruby_cms/templates/models/preference.rb', line 31 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
13 14 15 16 17 18 |
# File 'lib/generators/ruby_cms/templates/models/preference.rb', line 13 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
20 21 22 23 24 25 |
# File 'lib/generators/ruby_cms/templates/models/preference.rb', line 20 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
64 65 66 67 |
# File 'lib/generators/ruby_cms/templates/models/preference.rb', line 64 def assign_value(new_value) self.value_type ||= detect_type(new_value) self.value = serialize_value(new_value) end |
#typed_value ⇒ Object
53 54 55 56 57 58 59 60 61 62 |
# File 'lib/generators/ruby_cms/templates/models/preference.rb', line 53 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 |