Skip to content
Victor Rodrigues edited this page Aug 8, 2013 · 2 revisions

Let's say every user will keep their comments in a linked list. If you do:

comments = Hari('user#42').list(:comments)

=> #<Hari::Keys::List:0x007fcefb130cf0>

You get an object to call Redis list operations. If you want instead all the list members, call it with the hashbang !

Hari('user#42').list!(:comments)

=> ["First!", "OMG", "LOL"]

To bring the count of comments, there's no need to fetch all comments from Redis first. Call this instead, it's faster:

comments.count  # also .size or .length

comments.empty?
comments.one?
comments.many?

To get comments at specific positions in the list, you can do:

comments.first
comments.last

# comment at position 4
comments[4]  # also .at(4) or .index(4)

# comments between positions 3 and 5:
comments[3, 5] # also [3..5] or .range(3, 5)

comments.from(7) # comments from position 7 to end of list

comments.to(5)   # comments from start of list to position 5

More options to work with the comments list:

comments.members # all members

comments.include?('trololol') # or .member?('trololol')
                              # expensive for a list, because gets all members first

comments[6] = 'Good!' # sets element in position 6

# append to list

comments.rpush 'lol'
comments.add 'omg'
comments.push 'zomg'
comments << 'LOL'

# prepends to list
comments.lpush 'First!'

comments.insert 'LOL', 'OMG'
comments.insert_after 'LOL', 'OMG'  # inserts OMG after LOL

comments.insert_before 'LOL', 'OMG' # inserts OMG before LOL

comments.delete 'LOL' # deletes all ocurrences of LOL
comments.delete 'LOL', 2 # deletes first 2 ocurrences of LOL

comments.pop
comments.rpop  # deletes and brings last element in list

comments.shift
comments.lpop  # deletes and brings first element in list
Clone this wiki locally