class Sohm::BasicSet
Defines most of the methods used by `Set` and `MultiSet`.
Public Instance Methods
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]
# File lib/sohm.rb, line 397 def [](id) model[id] if exists?(id) end
Returns true
if id
is included in the set. Otherwise, returns false
.
Example:
class Post < Sohm::Model end class User < Sohm::Model set :posts, :Post end user = User.create post = Post.create user.posts.add(post) user.posts.exists?('nonexistent') # => false user.posts.exists?(post.id) # => true
# File lib/sohm.rb, line 419 def exists?(id) execute { |key| redis.call("SISMEMBER", key, id) == 1 } end
Returns an array with all the ID's of the set.
class Post < Sohm::Model end class User < Sohm::Model attribute :name index :name set :posts, :Post end User.create(name: "John") User.create(name: "Jane") User.all.ids # => ["1", "2"] User.find(name: "John").union(name: "Jane").ids # => ["1", "2"]
# File lib/sohm.rb, line 383 def ids execute { |key| redis.call("SMEMBERS", key) } end
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.
# File lib/sohm.rb, line 337 def include?(model) exists?(model.id) end
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)
# File lib/sohm.rb, line 358 def sample model[execute { |key| redis.call("SRANDMEMBER", key) }] end
Returns the total size of the set using SCARD.
# File lib/sohm.rb, line 342 def size execute { |key| redis.call("SCARD", key) } end