Sha256: f827fed9c8706dadbc21ed2540990dc28c3e778af97f345cf77c988b885d7117

Contents?: true

Size: 1.66 KB

Versions: 1

Compression:

Stored size: 1.66 KB

Contents

module Settingson::Base

  extend ActiveSupport::Concern

  module ClassMethods

    # Settings.configure do |config|
    #   config.cache.expires = 600   # default: 600
    #   config.cache.enabled = true  # default: true
    # end
    #
    # # or
    #
    # Settings.configure.cache.expires = 600
    # Settings.configure.cache.enabled = true
    def configure
      @_settings ||= ::Settingson::Config.new
      yield @_settings if block_given?
      @_settings
    end

    # Settings.defaults do |settings|
    #   settings.server.host = 'host'
    #   settings.server.port = 80
    # end
    def defaults
      return unless block_given?
      Rails.application.config.after_initialize do
        yield Settingson::Defaults.new( klass: self )
      end
    end

    # Settings.from_hash('smtp.host' => 'host')
    # Settings.smtp.host
    def from_hash(attributes)
      case attributes
      when Hash
        attributes.map{|k,v| find_or_create_by(key: k).update!(value: v)}
        Rails.cache.clear
        true
      else
        raise ArgumentError, 'Hash required', caller
      end
    end

    # Custom hook for clear cache before delete_all
    #
    def delete_all
      super
      Rails.cache.delete_matched(/#{self.configure.cache.namespace}/)
    end

    def method_missing(symbol, *args)
      super
    rescue NameError, NoMethodError
      Settingson::Store.new(klass: self).send(symbol, *args)
    end

  end # module ClassMethods

  included do
    serialize      :value
    before_destroy :__delete_cached
  end

  def __delete_cached
    cache_key = "#{self.class.configure.cache.namespace}/#{self.key}"
    Rails.cache.delete(cache_key)
  end

end # Settingson::Base

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
settingson-1.7.7 app/models/concerns/settingson/base.rb