Class: Ohm::MutableSet

Inherits:
Set
  • Object
show all
Defined in:
lib/ohm.rb

Instance Attribute Summary

Attributes inherited from Set

#key, #model, #namespace

Instance Method Summary collapse

Methods inherited from Set

#[], #combine, #except, #exists?, #find, #first, #ids, #include?, #initialize, #size, #sort, #sort_by, #union

Methods included from Collection

#each, #empty?, #fetch, #to_a, #to_json

Constructor Details

This class inherits a constructor from Ohm::Set

Instance Method Details

#add(model) ⇒ Object Also known as: <<

Add a model directly to the set.

Example:

user = User.create
post = Post.create

user.posts.add(post)

583
584
585
# File 'lib/ohm.rb', line 583

def add(model)
  redis.call("SADD", key, model.id)
end

#delete(model) ⇒ Object

Remove a model directly from the set.

Example:

user = User.create
post = Post.create

user.posts.delete(post)

598
599
600
# File 'lib/ohm.rb', line 598

def delete(model)
  redis.call("SREM", key, model.id)
end

#replace(models) ⇒ Object

Replace all the existing elements of a set with a different collection of models. This happens atomically in a MULTI-EXEC block.

Example:

user = User.create
p1 = Post.create
user.posts.add(p1)

p2, p3 = Post.create, Post.create
user.posts.replace([p2, p3])

user.posts.include?(p1)
# => false

618
619
620
621
622
623
624
625
626
627
628
# File 'lib/ohm.rb', line 618

def replace(models)
  ids = models.map(&:id)

  model.synchronize do
    redis.queue("MULTI")
    redis.queue("DEL", key)
    ids.each { |id| redis.queue("SADD", key, id) }
    redis.queue("EXEC")
    redis.commit
  end
end