Class: Sohm::BasicSet
Overview
Defines most of the methods used by ‘Set` and `MultiSet`.
Direct Known Subclasses
Instance Method Summary collapse
-
#[](id) ⇒ Object
Retrieve a specific element using an ID from this set.
-
#exists?(id) ⇒ Boolean
Returns
trueifidis included in the set. -
#ids ⇒ Object
Returns an array with all the ID’s of the set.
-
#include?(model) ⇒ Boolean
Check if a model is included in this set.
-
#sample ⇒ Object
SMEMBERS then choosing the first will take too much memory in case data grow big enough, which will be slow in this case.
-
#size ⇒ Object
Returns the total size of the set using SCARD.
Methods included from Collection
#each, #empty?, #fetch, #to_a, #to_json
Instance Method Details
#[](id) ⇒ Object
Retrieve a specific element using an ID from this set.
Example:
# Let's say we got the ID 1 from a request parameter.
id = 1
# Retrieve the post if it's included in the user's posts.
post = user.posts[id]
394 395 396 |
# File 'lib/sohm.rb', line 394 def [](id) model[id] if exists?(id) end |
#exists?(id) ⇒ Boolean
416 417 418 |
# File 'lib/sohm.rb', line 416 def exists?(id) execute { |key| redis.call("SISMEMBER", key, id) == 1 } end |
#ids ⇒ Object
380 381 382 |
# File 'lib/sohm.rb', line 380 def ids execute { |key| redis.call("SMEMBERS", key) } end |
#include?(model) ⇒ Boolean
Check if a model is included in this set.
Example:
u = User.create
User.all.include?(u)
# => true
Note: Ohm simply checks that the model’s ID is included in the set. It doesn’t do any form of type checking.
334 335 336 |
# File 'lib/sohm.rb', line 334 def include?(model) exists?(model.id) end |
#sample ⇒ Object
SMEMBERS then choosing the first will take too much memory in case data grow big enough, which will be slow in this case. Providing sample only gives a hint that we won’t preserve any order for this, there will be 2 cases:
-
Anyone in the set will do, this is the original use case of +sample*
-
For some reasons(maybe due to filters), we only have 1 element left
in this set, using sample will do the trick
For all the other cases, we won’t be able to fetch a single element without fetching all elements first(in other words, doing this efficiently)
355 356 357 |
# File 'lib/sohm.rb', line 355 def sample model[execute { |key| redis.call("SRANDMEMBER", key) }] end |
#size ⇒ Object
Returns the total size of the set using SCARD.
339 340 341 |
# File 'lib/sohm.rb', line 339 def size execute { |key| redis.call("SCARD", key) } end |