Sha256: aa6ef560c02eb8c4c3d01c80b86f77c451c627f9606f4370610c19f20fb6eec4

Contents?: true

Size: 1.86 KB

Versions: 3

Compression:

Stored size: 1.86 KB

Contents

module Blendris

  # RedisReferenceBase holds the methods that are common to
  # RedisReference objects and RedisReferenceSet objects.

  class RedisReferenceBase

    include RedisNode
    extend RedisAccessor

    def initialize(key, options = {})
      @model = options[:model]
      @key = sanitize_key(key)
      @reverse = options[:reverse]
      @options = options
      @on_change = options[:on_change]

      @klass = options[:class] || Model
      @klass = constantize(camelize @klass) if @klass.kind_of? String

      unless @klass.ancestors.include? Model
        raise ArgumentError.new("#{klass.name} is not a model")
      end
    end

    def apply_reverse_add(value)
      if @reverse && value
        reverse = value.redis_symbol(@reverse)
        reverse.assign_ref(@model) if !reverse.references @model
      end
    end

    def apply_reverse_delete(value)
      if @reverse && value
        reverse = value.redis_symbol(@reverse)
        reverse.remove_ref(@model) if reverse.references @model
      end
    end

    def self.cast_to_redis(obj, options = {})
      expect = options[:class] || Model
      expect = constantize(expect) if expect.kind_of? String
      expect = Model unless expect.ancestors.include? Model

      if obj == nil
        nil
      elsif obj.kind_of? expect
        obj.key
      else
        raise TypeError.new("#{obj.class.name} is not a #{expect.name}")
      end
    end

    def self.cast_from_redis(refkey, options = {})
      expect = options[:class] || Model
      expect = constantize(expect) if expect.kind_of? String
      expect = Model unless expect.ancestors.include? Model

      klass = constantize(redis.get(refkey)) if refkey

      if klass == nil
        nil
      elsif klass.ancestors.include? expect
        klass.new refkey
      else
        raise TypeError.new("#{klass.name} is not a #{expect.name}")
      end
    end

  end

end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
blendris-0.5 lib/blendris/reference_base.rb
blendris-0.0.4 lib/blendris/reference_base.rb
blendris-0.0.3 lib/blendris/reference_base.rb