Class: Commendo::RedisBacked::WeightedGroup

Inherits:
Object
  • Object
show all
Defined in:
lib/commendo/redis-backed/weighted_group.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key_base, *content_sets) ⇒ WeightedGroup

Returns a new instance of WeightedGroup.



8
9
10
11
12
# File 'lib/commendo/redis-backed/weighted_group.rb', line 8

def initialize(key_base, *content_sets)
  @redis = Redis.new(host: Commendo.config.host, port: Commendo.config.port, db: Commendo.config.database)
  @key_base = key_base
  @content_sets = content_sets
end

Instance Attribute Details

#content_setsObject

Returns the value of attribute content_sets.



6
7
8
# File 'lib/commendo/redis-backed/weighted_group.rb', line 6

def content_sets
  @content_sets
end

#key_baseObject

Returns the value of attribute key_base.



6
7
8
# File 'lib/commendo/redis-backed/weighted_group.rb', line 6

def key_base
  @key_base
end

#redisObject

Returns the value of attribute redis.



6
7
8
# File 'lib/commendo/redis-backed/weighted_group.rb', line 6

def redis
  @redis
end

#tag_setObject

Returns the value of attribute tag_set.



6
7
8
# File 'lib/commendo/redis-backed/weighted_group.rb', line 6

def tag_set
  @tag_set
end

Instance Method Details

#filtered_similar_to(resource, options = {}) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/commendo/redis-backed/weighted_group.rb', line 36

def filtered_similar_to(resource, options = {})
  if @tag_set.nil? || (options[:include].nil? && options[:exclude].nil?)
    return similar_to(resource, options[:limit] || 0)
  else
    similar = similar_to(resource)
    limit = options[:limit] || similar.length
    filtered = []
    similar.each do |s|
      return filtered if filtered.length >= limit
      filtered << s if @tag_set.matches(s[:resource], options[:include], options[:exclude])
    end
    return filtered
  end
end

#similar_to(resource, limit = 0) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/commendo/redis-backed/weighted_group.rb', line 14

def similar_to(resource, limit = 0)
  finish = limit -1
  resources = resource.kind_of?(Array) ? resource : [resource]
  keys = []
  weights = []
  content_sets.each do |cs|
    resources.each do |resource|
      keys << cs[:cs].similarity_key(resource)
      weights << cs[:weight]
    end
  end
  tmp_key = "#{key_base}:tmp:#{SecureRandom.uuid}"
  redis.zunionstore(tmp_key, keys, weights: weights)
  similar_resources = redis.zrevrange(tmp_key, 0, finish, with_scores: true)
  redis.del(tmp_key)

  similar_resources.map do |resource|
    {resource: resource[0], similarity: resource[1].to_f.round(3)}
  end

end