Last Updated: February 25, 2016
·
530
· beydogan

Rails appplication wide settings

This is a very simple class to store and get application wide settings using Redis as storage.

SETUP

You need to have 'redis-rails' gem in your Gemfile. And also have a redis server running in your environment. You can create an initializer to create Redis instance. A simple initializer would be;

config/initializers/redis.rb


REDIS = Redis.new

lib/setting.rb

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

USAGE

Modify DEFAULTS hash in setting.rb by your needs

Setting.set(:setting_1, true)
Setting.get(:setting_1) # true

PS; This is POC. might need some improvements

1 Response
Add your response

This approach is very slow on remote redis connection.

over 1 year ago ·