Class: ForgetTable::Distribution
- Inherits:
-
Object
- Object
- ForgetTable::Distribution
- Defined in:
- lib/forget_table/distribution.rb
Overview
Represents a categorical distribution composed by weighted bins.
A distribution is instantiated with the following parameters:
-
name: the name of the distribution
-
redis: the redis client that will host the distribution
Example of an instance:
distribution: "guitars"
bins: "fender" => 10, "gibson" => 20, "epi" => "30
Instance Attribute Summary collapse
-
#name ⇒ Object
readonly
Returns the value of attribute name.
Instance Method Summary collapse
-
#distribution(number_of_bins: -1,, with_scores: false) ⇒ Object
Returns the list of bins in the distribution.
- #hits_count ⇒ Object
-
#increment(bin:, amount: 1) ⇒ Object
Increments the bin score by the given amount.
-
#initialize(name:, redis:) ⇒ Distribution
constructor
A new instance of Distribution.
- #last_updated ⇒ Object
-
#score_for_bin(bin) ⇒ Object
Returns the score for the given bin.
Constructor Details
#initialize(name:, redis:) ⇒ Distribution
Returns a new instance of Distribution.
20 21 22 23 |
# File 'lib/forget_table/distribution.rb', line 20 def initialize(name:, redis:) @name = name @redis = redis end |
Instance Attribute Details
#name ⇒ Object (readonly)
Returns the value of attribute name.
18 19 20 |
# File 'lib/forget_table/distribution.rb', line 18 def name @name end |
Instance Method Details
#distribution(number_of_bins: -1,, with_scores: false) ⇒ Object
Returns the list of bins in the distribution. Params:
-
number_of_bins
-
options
45 46 47 48 49 50 51 52 53 54 |
# File 'lib/forget_table/distribution.rb', line 45 def distribution(number_of_bins: -1, with_scores: false) begin decrement! stop_bin = (number_of_bins == -1) ? -1 : (number_of_bins - 1) redis.zrevrange(name, 0, stop_bin, with_scores: with_scores) rescue RuntimeError [[]] end end |
#hits_count ⇒ Object
67 68 69 |
# File 'lib/forget_table/distribution.rb', line 67 def hits_count redis.get(hits_count_key).to_i end |
#increment(bin:, amount: 1) ⇒ Object
Increments the bin score by the given amount. params:
-
bin
-
amount
29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/forget_table/distribution.rb', line 29 def increment(bin:, amount: 1) redis.zincrby(name, amount, bin) # Increment the total number of hits stored_bins = redis.incrby(hits_count_key, 1) if stored_bins == 1 # Set the initial timestamp if never set redis.set(last_updated_at_key, Time.now.to_i) end end |
#last_updated ⇒ Object
63 64 65 |
# File 'lib/forget_table/distribution.rb', line 63 def last_updated redis.get(last_updated_at_key) end |
#score_for_bin(bin) ⇒ Object
Returns the score for the given bin
57 58 59 60 61 |
# File 'lib/forget_table/distribution.rb', line 57 def score_for_bin(bin) decrement! redis.zscore(name, bin) end |