Created
April 20, 2015 01:29
-
-
Save wacko/e93e0c6bac082d27e5fd to your computer and use it in GitHub Desktop.
Very simple and stupid key-value store using ActiveRecord
This file contains hidden or 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
# 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 |
This file contains hidden or 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
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