Sha256: c839c7bb02cca20b9b63b25cd760ddcbf3d037845af954739bb4512a15b9967b

Contents?: true

Size: 1.77 KB

Versions: 1

Compression:

Stored size: 1.77 KB

Contents

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

    after_create  :reset_owner_association
    after_destroy :reset_owner_association
    validate      :validate_format_of_name

    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 validate_format_of_name
      if name.blank?
        errors.add(:name, :blank)
      elsif !name.is_a?(String) || name !~ /^([a-z0-9]+_?)+$/
        errors.add(:name, :invalid)
      end
    end

    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.5 lib/has_settings/setting.rb