Skip to content

Instantly share code, notes, and snippets.

@carstengehling
Created September 9, 2013 12:47
Show Gist options
  • Save carstengehling/6495127 to your computer and use it in GitHub Desktop.
Save carstengehling/6495127 to your computer and use it in GitHub Desktop.
Simple application-wide flag setter/getter, using ActiveRecord as backend. Would anyone be interested in this as a fully working gem?
class AppState < ActiveRecord::Base
attr_accessible :key, :value
validates :key, presence: true
serialize :value
def self.get_value(key, default_value = nil)
as = AppState.find_by_key(key)
return default_value if as.blank?
as.value
end
def self.set_value(key, value)
as = AppState.find_or_initialize_by_key(key)
as.value = value
as.save
value
end
end
require 'spec_helper'
describe AppState do
describe "Validations" do
it { should validate_presence_of :key }
end
describe "set_value" do
it "should return the value set" do
a = Date.today
AppState.set_value(:test1, a).should == a
end
end
describe "get_value" do
it "should save and return the same value" do
a = Date.today
AppState.set_value(:test1, a)
AppState.get_value(:test1).should == a
end
it "should return a value of the same type, that it was set" do
a = Date.today
AppState.set_value(:test1, a)
AppState.get_value(:test1).class.should == a.class
a = true
AppState.set_value(:test1, a)
AppState.get_value(:test1).class.should == a.class
a = false
AppState.set_value(:test1, a)
AppState.get_value(:test1).class.should == a.class
a = { foo: "bar", xyzzy: 42 }
AppState.set_value(:test1, a)
AppState.get_value(:test1).class.should == a.class
end
it "should return default value from parameter, if value not already set" do
AppState.get_value(:test2, 42).should == 42
AppState.set_value(:test2, 99)
AppState.get_value(:test2, 42).should == 99
end
end
end
class CreateAppStates < ActiveRecord::Migration
def change
create_table :app_states do |t|
t.string :key
t.text :value
t.timestamps
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment