Class: Commendo::WeightedGroup

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(redis, key_base, *content_sets) ⇒ WeightedGroup

Returns a new instance of WeightedGroup.



7
8
9
# File 'lib/commendo/weighted_group.rb', line 7

def initialize(redis, key_base, *content_sets)
  @content_sets, @redis, @key_base = content_sets, redis, key_base
end

Instance Attribute Details

#content_setsObject

Returns the value of attribute content_sets.



5
6
7
# File 'lib/commendo/weighted_group.rb', line 5

def content_sets
  @content_sets
end

#key_baseObject

Returns the value of attribute key_base.



5
6
7
# File 'lib/commendo/weighted_group.rb', line 5

def key_base
  @key_base
end

#redisObject

Returns the value of attribute redis.



5
6
7
# File 'lib/commendo/weighted_group.rb', line 5

def redis
  @redis
end

#tag_setObject

Returns the value of attribute tag_set.



5
6
7
# File 'lib/commendo/weighted_group.rb', line 5

def tag_set
  @tag_set
end

Instance Method Details

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



33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/commendo/weighted_group.rb', line 33

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



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/commendo/weighted_group.rb', line 11

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