Class: KVC::Settings

Inherits:
ActiveRecord::Base
  • Object
show all
Defined in:
lib/kvc/settings.rb

Overview

KVC::Settings is a model rarely accessed like other Active Record models. You can still fetch records from the database as in other models, but you will more likely read and write records through the KVC namespace directly:

KVC.key = "value"
# Creates #<KVC::Settings id: 1, key: "key", value: "---\n\"value\"">
# Values are serialized to accommodate complex object storage.

KVC.key # => "value"
# Fetches #<KVC::Settings id: 1, key: "key", value: "---\n\"value\"">

Constant Summary collapse

@@strict_keys =

Do not raise exceptions on keys that don’t exist.

false
@@reload_records =

Reload serialized ActiveRecord::Base records.

true
@@validations =
HashWithIndifferentAccess.new []

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.config(&block) ⇒ Object

Config takes a block for configuration. For now, this provides rudimentary validation. E.g.:

KVC::Settings.config do
  validates("username") { |value| value.is_a? String }
  validates("username") { |value| (2..16).include? value.to_s.length }
end


34
35
36
37
38
39
40
41
# File 'lib/kvc/settings.rb', line 34

def config(&block)
  Object.new.instance_eval do
    def validates(*args, &proc)
      @@validations[args] << proc
    end
    self
  end.instance_eval(&block)
end

.deserialize(object) ⇒ Object

Recursively reload saved records. To short-circuit record reloading, set KVC::Settings.reload_records = false.



45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/kvc/settings.rb', line 45

def deserialize(object)
  return object unless reload_records?

  case object
  when ActiveRecord::Base
    object.new_record? ? object : object.reload
  when Array
    object.map { |o| deserialize(o) }
  when Hash
    object.each { |k, v| object[k] = deserialize(v) }
  else
    object
  end
end

Instance Method Details

#valueObject

Deserializes value from database.



68
69
70
# File 'lib/kvc/settings.rb', line 68

def value
  @value ||= KVC::Settings.deserialize YAML.load(read_attribute(:value))
end

#value=(input) ⇒ Object

Serializes value for database.



73
74
75
# File 'lib/kvc/settings.rb', line 73

def value=(input)
  write_attribute :value, (@value = input).to_yaml
end