Module: HasSettings::ActiveRecordExtension::ClassMethods

Defined in:
lib/has_settings/active_record_extension.rb

Instance Method Summary collapse

Instance Method Details

#has_settings(&block) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/has_settings/active_record_extension.rb', line 4

def has_settings(&block)
  settings_class = HasSettings.ensure_settings_class(self)
  settings_class.instance_eval(&block)

  has_many :settings, :class_name => settings_class.name, :dependent => :destroy do

    def build(*setting_names)
      setting_names.each do |setting_name|
        self << proxy_reflection.klass.new(:name => setting_name.to_s)
      end
    end

    # Define the settings query methods, e.g. +account.settings.wiffle?+
    settings_class.list.each do |key|
      # The query method, does this account have a given setting? account.settings.wiffle?
      define_method "#{key}?" do
        any? { |setting| setting.name.to_sym == key }
      end

      # The finder method which returns the setting if present, otherwise a new instance, allows
      # non-destructive create and delete operations:
      #
      #   account.settings.wiffle.destroy
      #   account.settings.wiffle.create
      #
      define_method "#{key}" do
        instance = detect { |setting| setting.name.to_sym == key }
        instance ||= settings_class.new(@owner.class.name.underscore.to_sym => @owner, :name => key.to_s)
      end
    end
  end

  include HasSettings::ActiveRecordExtension::InstanceMethods
  alias_method_chain :update_attributes, :settings
  alias_method_chain :update_attributes!, :settings

end