Sha256: fc69e25d7c1c0ad156a896089ddab76b91eb633600a91298c0d64a79220aab0b

Contents?: true

Size: 1.82 KB

Versions: 3

Compression:

Stored size: 1.82 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)
      when Array
        KeywordSets.new(prefix, keywords.join(' '), field)
      else
        raise TypeError, ":keywords should only be a String or Range"
      end
    end
  end
  
  class FuzzySets < 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
      words.map { |w| ns[Lunar.encode(w)] }
    end

    def ns
      @ns ||= Lunar.nest[prefix][:Fuzzy][field]
    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 { |id| Lunar.redis.zadd key, 1, id }
      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

3 entries across 3 versions & 1 rubygems

Version Path
lunar-0.4.1 lib/lunar/sets.rb
lunar-0.4.0 lib/lunar/sets.rb
lunar-0.3.0 lib/lunar/sets.rb