Permalink
Find file
Fetching contributors…
Cannot retrieve contributors at this time
66 lines (48 sloc) 1.85 KB
# This Settings module allows you to easily add the settings functionality to any object class throughout the app.
# Will simplify this: User.find(1).settings.find_by_key('key').value
# To: User.find(1).key
#
# Also creates an Object.update_settings! method to easily add new settings to already existing objects.
module Settings
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
attr_reader :available_settings
def setting(key, options = {})
# Inject the association for the settings if this is the first setting loaded for the class
unless self.reflect_on_association(:settings)
has_many :settings, as: :resource
accepts_nested_attributes_for :settings
end
@available_settings ||= {}
@available_settings[key] = options unless available_settings.has_key?(key)
define_method key do
send("find_#{key}").value rescue nil
end
define_method "#{key}?" do
send(key).present?
end
define_method "find_#{key}" do
@settings ||= settings
@settings.find { |setting| setting.key == key }
end
define_method "update_#{key}!" do |value|
send("find_#{key}").update_attribute(:value, value)
end
define_method :editable_settings do
settings.where(key: self.class.available_settings.select { |k,v| v[:editable]}.keys )
end
class << self
define_method :update_settings! do
existing_settings = first.settings.pluck(:key).collect(&:to_sym) rescue []
(available_settings.keys - existing_settings).each do |new_key|
all.each { |object| object.settings.create(key: new_key, value: available_settings[new_key][:default]) }
end
end
end
end
end
end
# Add Settings capabilities to ActiveRecord
ActiveRecord::Base.send :include, Settings