Skip to content

Instantly share code, notes, and snippets.

@wacko
Created April 20, 2015 01:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wacko/e93e0c6bac082d27e5fd to your computer and use it in GitHub Desktop.
Save wacko/e93e0c6bac082d27e5fd to your computer and use it in GitHub Desktop.
Very simple and stupid key-value store using ActiveRecord
# Use KeyValue to store globally unique data
KeyValue.set('api_key', '123') # => true
KeyValue.get('api_key') # => '123'
# You can use the alternate syntax:
KeyValue['api_key'] = '123' # => true
KeyValue['api_key'] # => '123'
# It return `nil` for undefined keys:
KeyValue.get('undefined') # => nil
class KeyValue < ActiveRecord::Base
attr_accessible :key, :value
def self.get(key)
where(key: key).first.try :value
end
def self.set(key, value)
where(key: key).first!.update_column(:value, value)
rescue
create(key: key, value: value)
end
class << self
alias_method :[], :get
alias_method :[]=, :set
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment