Sha256: 0a054f2cfcca549e782e33fa9fcb0ac313226b88005b100eeb66737a11cd7032

Contents?: true

Size: 1.53 KB

Versions: 1

Compression:

Stored size: 1.53 KB

Contents

module HasSettings
  class Setting < ActiveRecord::Base
    abstract_class = true

    after_create   :reset_owner_association
    after_destroy  :reset_owner_association

    def create
      if new_record?
        super
      end
      self
    end

    def self.setting(key, options = nil)
      @settings ||= {}
      @settings[key] = options && options[:protected]
    end

    def self.list
      @settings.keys
    end

    def self.table_name
      name.tableize
    end

    def self.protected?(key)
      @settings[key]
    end

    def protected?
      self.class.protected?(self.name.to_sym)
    end

    private

    def owner_class_instance
      send(self.class.owner_class_sym)
    end

    def update_owner_timestamp
      owner_class_instance.update_attribute(:updated_at, Time.now) if owner_class_instance && !owner_class_instance.new_record?
    end

    def reset_owner_association
      owner_class_instance.settings.reload
    end

    def self.owner_class=(owner_class)
      @owner_class_sym = owner_class.name.underscore.to_sym
      belongs_to              owner_class_sym
      validates_presence_of   owner_class_sym
      validates_uniqueness_of :name, :scope => owner_class_key_sym

      if owner_class.table_exists? && owner_class.column_names.include?('updated_at')
        before_create   :update_owner_timestamp
        before_destroy  :update_owner_timestamp
      end
    end

    def self.owner_class_sym
      @owner_class_sym
    end

    def self.owner_class_key_sym
      "#{owner_class_sym}_id".to_sym
    end
  end

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
has_settings-0.0.4 lib/has_settings/setting.rb