class Sohm::List
Attributes
Public Class Methods
# File lib/sohm.rb, line 189 def initialize(key, namespace, model) @key = key @namespace = namespace @model = model end
Public Instance Methods
Delete a model from the list.
Note: If your list contains the model multiple times, this method will delete all instances of that model in one go.
Example:
class Comment < Sohm::Model end class Post < Sohm::Model list :comments, :Comment end p = Post.create c = Comment.create p.comments.push(c) p.comments.push(c) p.comments.delete(c) p.comments.size == 0 # => true
# File lib/sohm.rb, line 284 def delete(model) # LREM key 0 <id> means remove all elements matching <id> # @see http://redis.io/commands/lrem redis.call("LREM", key, 0, model.id) end
Returns the first element of the list using LINDEX.
# File lib/sohm.rb, line 201 def first model[redis.call("LINDEX", key, 0)] end
Returns an array with all the ID's of the list.
class Comment < Sohm::Model end class Post < Sohm::Model list :comments, :Comment end post = Post.create post.comments.push(Comment.create) post.comments.push(Comment.create) post.comments.push(Comment.create) post.comments.map(&:id) # => ["1", "2", "3"] post.comments.ids # => ["1", "2", "3"]
# File lib/sohm.rb, line 310 def ids redis.call("LRANGE", key, 0, -1) end
Checks if the model is part of this List
.
An important thing to note is that this method loads all of the elements of the List
since there is no command in Redis that allows you to actually check the list contents efficiently.
You may want to avoid doing this if your list has say, 10K entries.
# File lib/sohm.rb, line 245 def include?(model) ids.include?(model.id) end
Returns the last element of the list using LINDEX.
# File lib/sohm.rb, line 206 def last model[redis.call("LINDEX", key, -1)] end
Pushes the model to the end of the list using RPUSH.
# File lib/sohm.rb, line 250 def push(model) redis.call("RPUSH", key, model.id) end
Returns an array of elements from the list using LRANGE. range
receives 2 integers, start and stop
Example:
class Comment < Sohm::Model end class Post < Sohm::Model list :comments, :Comment end c1 = Comment.create c2 = Comment.create c3 = Comment.create post = Post.create post.comments.push(c1) post.comments.push(c2) post.comments.push(c3) [c1, c2] == post.comments.range(0, 1) # => true
# File lib/sohm.rb, line 234 def range(start, stop) fetch(redis.call("LRANGE", key, start, stop)) end
Returns the total size of the list using LLEN.
# File lib/sohm.rb, line 196 def size redis.call("LLEN", key) end
Pushes the model to the beginning of the list using LPUSH.
# File lib/sohm.rb, line 255 def unshift(model) redis.call("LPUSH", key, model.id) end
Private Instance Methods
# File lib/sohm.rb, line 316 def redis model.redis end