Class: Sohm::BasicSet

Inherits:
Object
  • Object
show all
Includes:
Collection
Defined in:
lib/sohm.rb

Overview

Defines most of the methods used by ‘Set` and `MultiSet`.

Direct Known Subclasses

Set

Instance Method Summary collapse

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]


397
398
399
# File 'lib/sohm.rb', line 397

def [](id)
  model[id] if exists?(id)
end

#exists?(id) ⇒ Boolean

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

Returns:

  • (Boolean)


419
420
421
# File 'lib/sohm.rb', line 419

def exists?(id)
  execute { |key| redis.call("SISMEMBER", key, id) == 1 }
end

#idsObject

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"]


383
384
385
# File 'lib/sohm.rb', line 383

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.

Returns:

  • (Boolean)


337
338
339
# File 'lib/sohm.rb', line 337

def include?(model)
  exists?(model.id)
end

#sampleObject

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:

  1. Anyone in the set will do, this is the original use case of +sample*

  2. 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)



358
359
360
# File 'lib/sohm.rb', line 358

def sample
  model[execute { |key| redis.call("SRANDMEMBER", key) }]
end

#sizeObject

Returns the total size of the set using SCARD.



342
343
344
# File 'lib/sohm.rb', line 342

def size
  execute { |key| redis.call("SCARD", key) }
end