Module: HasSetting::ClassMethods

Defined in:
lib/has_setting/ar_extensions.rb

Instance Method Summary collapse

Instance Method Details

#has_setting(name, options = {}) ⇒ Object

Setup of the getter/setter

Raises:

  • (ArgumentError)


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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/has_setting/ar_extensions.rb', line 7

def has_setting(name, options = {})
  name = name.to_s
  raise ArgumentError.new('Setting name must not be blank') if name.blank?

  self.class_eval do
    unless @has_setting_options # define only once
      # AR association to settings
      has_many( :settings, :as => :owner, :class_name => 'HasSetting::Setting',
                :foreign_key => :owner_id, :dependent => :destroy)
      after_save(:save_has_setting_association)
      @has_setting_options = {}
      def self.has_setting_options
        @has_setting_options
      end

      private
      # Callback to save settings
      def save_has_setting_association
        self.settings.each do |setting|
          setting.save if setting.changed?
        end
      end
    end
  end

  raise ArgumentError.new("Setting #{name }is already defined on #{self.name}") if self.has_setting_options.has_key?(name)

  # default options
  type = options[:type] || :string    # treat as string
  options[:localize] ||= false
  options[:no_fallback] ||= false
  self.has_setting_options[name] = options

  # setter
  define_method("#{name}=".intern) do |value|
    formatter = HasSetting::Formatters.for_type(type)
    write_setting(name, formatter.to_s(value))
  end

  # getter
  define_method(name) do |*args|
    setting = read_setting(name)
    options = args.first || has_setting_option(name)
    if setting.nil?
      result =
        if options[:default].is_a?(Proc)
          instance_exec(&options[:default])
        else
          options[:default]
        end
      return result
    end
    formatter = Formatters.for_type(options[:type] || type)
    formatter.to_type(setting.value)
  end
end