Last active
August 29, 2015 14:16
-
-
Save adriancuadros/6cbec9589c556016aafd to your computer and use it in GitHub Desktop.
Simple Redis Hash <=> Ruby Object Interface
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
require 'redis' | |
require 'active_support' | |
require 'active_support/core_ext' | |
module RedisHash | |
delegate :redis, :redis_base, to: :class | |
def self.included(base) | |
base.extend ClassMethods | |
base.send :attr_accessor, :id | |
base.send :mattr_accessor, :redis, :redis_base | |
base.redis ||= Redis.new | |
base.redis_base = base.name | |
end | |
module ClassMethods | |
def count | |
redis.get("#{redis_base}:count").to_i | |
end | |
def find(id) | |
raw_hash = redis.hgetall("#{redis_base}:#{id}") | |
unless raw_hash.empty? | |
found = new(raw_hash) | |
found.id = id | |
found | |
end | |
end | |
def create(args={}) | |
new(args).save | |
end | |
end | |
def save | |
redis.hmset("#{redis_base}:#{@id = current_id}", *@args) | |
redis.incr("#{redis_base}:count") | |
self | |
end | |
def update(args) | |
@args.merge!(args) | |
save | |
end | |
def destroy | |
redis.del(redis_base) | |
end | |
# Easy mass assignment | |
def initialize(args={}) | |
(@args = args).each do |key, value| | |
self.class.send(:define_method, key){ @args[key] } | |
self.class.send(:define_method, "#{key}="){|new_val| @args[key] = new_val } | |
end | |
end | |
private | |
def current_id | |
@id || self.class.count | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment