From 6d5a625ea6274a84ed795f3e36dbf1fd42715c70 Mon Sep 17 00:00:00 2001 From: Ben Kurtovic Date: Fri, 13 Mar 2015 03:33:30 -0500 Subject: [PATCH] Make admin settings more efficient and safer. --- app/controllers/admin_controller.rb | 4 +--- app/models/admin_setting.rb | 15 ++++++++++++--- db/seeds.rb | 8 ++++---- 3 files changed, 17 insertions(+), 10 deletions(-) diff --git a/app/controllers/admin_controller.rb b/app/controllers/admin_controller.rb index 7514495..f6e1a95 100644 --- a/app/controllers/admin_controller.rb +++ b/app/controllers/admin_controller.rb @@ -3,10 +3,8 @@ class AdminController < ApplicationController end def update - if !params[:settings].nil? + if params[:settings].is_a? Hash params[:settings].each do |key, value| - ## assert in list of valid settings... - ## only if changed (i.e. not equal to get) AdminSetting.set(key, value) end end diff --git a/app/models/admin_setting.rb b/app/models/admin_setting.rb index 63b5c5f..934b804 100644 --- a/app/models/admin_setting.rb +++ b/app/models/admin_setting.rb @@ -1,12 +1,21 @@ class AdminSetting < ActiveRecord::Base + def self.add(key, value) + self.create(key: key, value: value) + end + def self.get(key) - Rails.cache.fetch("admin_setting/#{key}") do - self.find_by(key: key).value - end + existing = Rails.cache.read("admin_setting/#{key}") + return existing unless existing.nil? + setting = self.find_by(key: key) + return nil if setting.nil? + Rails.cache.write("admin_setting/#{key}", setting.value) + setting.value end def self.set(key, value) + existing = self.get(key) + return if existing.nil? || existing == value self.find_by(key: key).update(value: value) Rails.cache.write("admin_setting/#{key}", value) end diff --git a/db/seeds.rb b/db/seeds.rb index 2aa9002..1a4caa5 100644 --- a/db/seeds.rb +++ b/db/seeds.rb @@ -6,7 +6,7 @@ # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) -AdminSetting.create(key: 'site_name', value: 'Your Corporation Site') -AdminSetting.create(key: 'corporation', value: 'Your Corporation') -AdminSetting.create(key: 'description', value: 'Your corporation\'s description goes here!') -AdminSetting.create(key: 'copyright', value: 'Your Corporation/Your Name') +AdminSetting.add('site_name', 'Your Corporation Site') +AdminSetting.add('corporation', 'Your Corporation') +AdminSetting.add('description', 'Your corporation\'s description goes here!') +AdminSetting.add('copyright', 'Your Corporation/Your Name')