Skip to content

Instantly share code, notes, and snippets.

@adriancuadros
Last active August 29, 2015 14:16
Show Gist options
  • Save adriancuadros/6cbec9589c556016aafd to your computer and use it in GitHub Desktop.
Save adriancuadros/6cbec9589c556016aafd to your computer and use it in GitHub Desktop.
Simple Redis Hash <=> Ruby Object Interface
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