Sha256: 5b0ccb1cc1239efa6cc922f2458789876fa35c00eb4c580dde0ad08957ef74a3

Contents?: true

Size: 1.45 KB

Versions: 2

Compression:

Stored size: 1.45 KB

Contents

module Lunar
  module Sets
    def self.new(prefix, keywords, field = '*')
      case keywords
      when String
        KeywordSets.new(prefix, keywords, field)
      when Range
        RangeSets.new(prefix, keywords, field)
      else
        raise TypeError, ":keywords should only be a String or Range"
      end
    end
  end
  
  class RangeSets < Array
    attr :prefix, :field, :range

    def initialize(prefix, range, field)
      @prefix = prefix
      @field  = field
      @range  = range
    
      super [write_and_retrieve_key]
    end
    
    def write_and_retrieve_key
      zrange = Lunar.redis.zrangebyscore(Lunar.nest[prefix][field], 
                                         @range.first, @range.last)
      zrange.each do |id|
        Lunar.redis.zadd key, 1, id 
      end
      # TODO :expire the key in X seconds where X is customizable
      key.to_s
    end

    def key
      @key ||= Lunar.nest[prefix][field]["#{ range.first }_TO_#{ range.last }"]
    end
  end

  class KeywordSets < Array
    attr :prefix, :words, :field

    def initialize(prefix, keywords, field = '*')
      @prefix = prefix
      @field  = field
      @words = Words.new(keywords)

      super(redis_set_keys)
    end
  
  protected
    def redis_set_keys
      keys_for_each_word.map { |key| Lunar.redis.keys(key) }.flatten
    end

    def keys_for_each_word
      words.map { |w| ns[Lunar.encode(w)] }
    end

    def ns
      @ns ||= Lunar.nest[prefix][field]
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
lunar-0.2.1 lib/lunar/sets.rb
lunar-0.2.0 lib/lunar/sets.rb