Sha256: d1d7b56f61ab4348d2f6ca19bdd3846aaf438f22d0bd7b3d042c5095a1804b08
Contents?: true
Size: 1.96 KB
Versions: 1
Compression:
Stored size: 1.96 KB
Contents
module RedisBackedModel class RedisBackedModel def self.find(*args) found = [] args.flatten.each do |id| attributes = $redis.hgetall("#{self.to_s.underscore}:#{id}") found << self.new(attributes.merge({'id' => id})) if attributes.size > 0 end (found.count == 1) ? found.first : found end def initialize(attributes={}) if attributes.class == Hash attributes.each do |key, value| add_to_instance_variables(key, value) end else raise ArgumentError end end def to_redis redis_commands = [] redis_commands << id_set_command instance_variables.each do | var | build_command_for_variable(var, redis_commands) end redis_commands end private attr_reader :id def add_to_instance_variables(key, value) if key.match(/score_\[\w+\|\w+\]/) add_to_scores(key, value) else self.instance_variable_set("@#{key}", value) end end def add_to_scores(key, value) scores << SortedSet.new(self.class, id, Hash[key,value]) end def build_command_for_variable(variable, collection) value = instance_variable_get(variable) if value.respond_to?(:each) value.each do |redis_object| collection << redis_object.to_redis end else collection << instance_variable_to_redis(variable) end end def id_set_command "sadd|#{model_name_for_redis}_ids|#{id}" end def instance_variable_to_redis(instance_variable) "hset|#{model_name_for_redis}:#{id}|#{instance_variable.to_s.deinstance_variableize}|#{instance_variable_get(instance_variable.to_s)}" end def model_name_for_redis class_as_string = self.class.to_s.demodulize.underscore end def scores @scores ||= [] end end end
Version data entries
1 entries across 1 versions & 1 rubygems
Version | Path |
---|---|
redis_backed_model-0.0.5 | lib/redis_backed_model/redis_backed_model.rb |