# Option model holds key-value options.
#
# To avoid conflicts, it is recommended to use ":" to namespace the keys, for example:
# Key: 'app:version', Value: '1.0.0'
#
# `Option.set` is preferred to `Option.new`.
# `Option.get` is preferred to `Option.find*` methods.
class Option < ApplicationRecord
  validates :key, presence: true
  validates :value, presence: true

  def key=(key)
    self[:key] = self.class.sanitize_key key
  end

  def value=(value)
    self[:value] = self.class.sanitize_value value
  end

  class << self
    def has?(key)
      !Option.find_by(key: sanitize_key(key)).nil?
    end

    def get(key, default_value = nil)
      option = Option.find_by(key: sanitize_key(key))
      option.nil? ? default_value : option.value
    end

    def set(key, value)
      option = Option.find_by(key: sanitize_key(key)) || Option.new(key: key)
      option.value = value
      option.save
      option.value
    end

    def sanitize_key(key)
      key.strip
    end

    def sanitize_value(value)
      value.strip
    end
  end
end
