Module: HasSetting

Extended by:
ActiveSupport::Concern
Defined in:
lib/has_setting/version.rb,
lib/has_setting/formatters.rb,
lib/has_setting/ar_extensions.rb

Defined Under Namespace

Modules: ClassMethods, Formatters Classes: Setting

Constant Summary collapse

VERSION =
"1.0.4"

Instance Method Summary collapse

Instance Method Details

#has_setting_option(name) ⇒ Object



95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/has_setting/ar_extensions.rb', line 95

def has_setting_option name
  klass = self.class
  option = klass.has_setting_options ? klass.has_setting_options[name] : nil
  while option.nil? and
        klass.superclass != ActiveRecord::Base
    klass = klass.superclass
    if klass.respond_to?(:has_setting_options) and klass.has_setting_options
      option = klass.has_setting_options[name]
    end
  end
  option
end

#localize?(name) ⇒ Boolean

Returns:

  • (Boolean)


85
86
87
88
# File 'lib/has_setting/ar_extensions.rb', line 85

def localize? name
  options = has_setting_option name
  options ? options[:localize] : false
end

#no_fallback?(name) ⇒ Boolean

Returns:

  • (Boolean)


90
91
92
93
# File 'lib/has_setting/ar_extensions.rb', line 90

def no_fallback? name
  options = has_setting_option name
  options ? options[:no_fallback] : false
end

#read_setting(name) ⇒ Object



76
77
78
79
80
81
82
83
# File 'lib/has_setting/ar_extensions.rb', line 76

def read_setting(name)
  # use detect instead of SQL find. like this the 'cached' has_many-collection is inited
  # only once
  locale = localize?(name) ? I18n.locale.to_s : ""
  s = self.settings.detect() {|item| item.name == name and item.locale.to_s == locale} # first see if there is a setting with current locale
  s ||= self.settings.detect() {|item| item.name == name} unless no_fallback?(name) # then if not found, take the first setting with matching name (TODO: add locale fallbacks)
  s
end

#write_setting(name, value) ⇒ Object



65
66
67
68
69
70
71
72
73
74
# File 'lib/has_setting/ar_extensions.rb', line 65

def write_setting(name, value)
  # find an existing setting or build a new one
  locale = localize?(name) ? I18n.locale : nil
  setting = self.settings.detect() {|item| item.name == name and item.locale.to_s == locale.to_s }
  setting = self.settings.build(:name => name, locale: locale) if setting.blank?
  setting.value = value
  # mark model as changed to make sure model is saved so that after_save is triggered even if only settings change
  # maybe there is a better way of doing this.
  self.updated_at = Time.now if self.respond_to?(:updated_at)
end