Sha256: f3577f66bfc01789db219560061fc41d7b0b962b4879a831bb5a8939c1cfa535

Contents?: true

Size: 1.42 KB

Versions: 1

Compression:

Stored size: 1.42 KB

Contents

module Lunar
  class Index
    attr :ns
  
    def self.create(prefix)
      new(prefix).tap { |i| yield i }.index
    end

    def self.delete(prefix, key)
      new(prefix).tap { |i| i.key key }.delete 
    end

    def initialize(prefix, redis = nil)
      @ns    = Lunar.nest[prefix]
      @attrs = {}
      @redis = (redis || Lunar.redis)
    end

    def key(key = nil)
      @key = key if key
      @key
    end

    def attrs=(attrs)
      attrs.each { |k, v| attr k, v } 
    end

    def attr(field, value = nil)
      @attrs[field.to_sym] = value if value
      @attrs[field.to_sym]
    end

    def index
      @attrs.each do |field, value|
        scoring = Scoring.new(value)
        words   = []
        scoring.scores.each do |word, score|
          words << word
          @redis.zadd @ns[field][Lunar.encode(word)], score, key
          @redis.sadd @ns[key][field], word
        end

        unused_words = @redis.smembers(@ns[key][field]) - words
        unused_words.each do |word|
          @redis.zrem @ns[field][Lunar.encode(word)], key
          @redis.srem @ns[key][field], word
        end
      end

      return self
    end

    def delete
      keys = @redis.keys @ns[key]['*']
      keys.each do |k|
        field = k.gsub("#{ @ns[key] }:", '')
        words = @redis.smembers(k)
        words.each do |w|
          @redis.zrem @ns[field][Lunar.encode(w)], key
        end
        @redis.del k 
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
lunar-0.1.1 lib/lunar/index.rb