Skip to content

Instantly share code, notes, and snippets.

@nchapman
Created August 15, 2010 20:39
Show Gist options
  • Save nchapman/525929 to your computer and use it in GitHub Desktop.
Save nchapman/525929 to your computer and use it in GitHub Desktop.
require 'redis/list'
require 'redis/value'
class RedisModel
include ActiveModel::Validations
include ActiveModel::Conversion
extend ActiveModel::Naming
attr_accessor :id
def initialize(attributes = {})
attributes.each { |name, value| send("#{name}=", value) }
end
def self.create(attributes)
model.new(attributes).save
end
def self.first
find(rlist("#{key}:all").first)
end
def self.find(id)
rvalue("#{key}:#{id}").value
end
def self.last
find(rlist("#{key}:all").last)
end
def self.collect(ids)
ids.collect { |id| find(id) }
end
def self.collect_by_key(key)
collect(rlist(key).values)
end
def destroy
rvalue("#{self.class.key}:#{self.id}").delete
rlist("#{self.class.key}:all").delete(self.id)
end
def new_record?
id.nil?
end
def save
if valid?
self.id = ActiveSupport::SecureRandom.hex(16) if new_record?
rvalue("#{self.class.key}:#{self.id}").value = self
rlist("#{self.class.key}:all") << self.id
return true
else
return false
end
end
# Redis helpers
def self.key
model_name.tableize
end
def self.rvalue(key)
Redis::Value.new(key, :marshal => true)
end
def rvalue(key)
self.class.rvalue(key)
end
def self.rlist(key)
Redis::List.new(key)
end
def rlist(key)
self.class.rlist(key)
end
def persisted?
false
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment