Skip to content

Instantly share code, notes, and snippets.

@beydogan
Last active October 25, 2015 11:34
Show Gist options
  • Save beydogan/ec57a1d4ede06334cc95 to your computer and use it in GitHub Desktop.
Save beydogan/ec57a1d4ede06334cc95 to your computer and use it in GitHub Desktop.
Rails application wide settings storage using Redis
# Class to store and get application-wide settings by using Redis as storage
# REDIS might be defined in an initiliazier. As following.
# REDIS = Redis.new
# @example
# Setting.set(:setting_1, true)
# Setting.get(:setting_1) # true
class Setting
DEFAULTS = {
setting_1: false
setting_2: 5
setting_3: "String"
}
def self.get(key)
(value = REDIS.get(key)) ? parse(key.to_sym,value) : DEFAULTS[key.to_sym]
end
def self.set(key, value)
REDIS.set(key.to_sym, value)
end
# Parse values by their default value's type. Redis only returns String
def self.parse(key, value)
klass = DEFAULTS[key].class
if klass == FalseClass || klass == TrueClass #Handle Boolean
return (value == "true")
elsif klass == Fixnum
value.to_i
elsif klass == Float
value.to_f
else
return value
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment