Last active
January 3, 2016 19:49
-
-
Save nhocki/af7d1803496f29605f60 to your computer and use it in GitHub Desktop.
Simple global settings stored on Redis
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Redis persisted class to save global settings. | |
class Settings | |
class << self | |
SETTER_MATCHER = /=$/.freeze | |
BOOLEAN_MATCHER = /\?$/.freeze | |
def redis | |
# TODO: use other redis instance? | |
@redis ||= Redis.new(RedisConfig[:statistic_counter]) | |
end | |
def method_missing(key, *args, &block) | |
if key.to_s =~ SETTER_MATCHER | |
redis.hset(namespace, key.to_s.gsub(SETTER_MATCHER, ''), *args) | |
reload! | |
elsif key.to_s =~ BOOLEAN_MATCHER | |
key = key.to_s.gsub(BOOLEAN_MATCHER, '') | |
::Truth.true?(all[key]) | |
else | |
all[key.to_s] | |
end | |
end | |
def namespace | |
'settings:members'.freeze | |
end | |
def all | |
Rails.cache.fetch(cache_key, expires_in: 15.minutes) do | |
redis.hgetall(namespace) | |
end | |
end | |
def replace(settings_hash) | |
redis.hmset(namespace, *settings_hash) | |
reload! | |
end | |
def cache_key | |
'global-settings'.freeze | |
end | |
def expire_cache | |
Rails.cache.delete(cache_key) | |
end | |
def reload! | |
expire_cache | |
all | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'spec_helper' | |
describe Settings do | |
it "behaves like a open struct" do | |
Settings.hearts_count = 1 | |
Settings.hearts_count.should == "1" | |
end | |
it "gets the booleans value for keys ending with ?" do | |
Settings.survey_active = true | |
Settings.survey_active?.should == true | |
Settings.survey_active = false | |
Settings.survey_active?.should == false | |
end | |
describe "#all" do | |
it "returns a hash with all the settings" do | |
Settings.some_setting = "hello" | |
Settings.another_setting = "world" | |
Settings.all.should eql({"some_setting" => "hello", "another_setting" => "world"}) | |
end | |
end | |
describe "#replace" do | |
it "replaces settings with a given hash" do | |
Settings.some_setting = "hello" | |
Settings.another_setting = "yeah" | |
Settings.replace("some_setting" => "world", "another_setting" => "woot!") | |
Settings.some_setting.should eql("world") | |
Settings.another_setting.should eql("woot!") | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment