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

Instance Method Details

#similar_to(resource) ⇒ Object



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

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

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

end