Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ohm & Redis: when to use set, list or collection?

What is the difference between a collection and a set or list when using Ohm & Redis?

Several of the Ohm examples use a list rather than a collection (see the list doc itself):

class Post < Ohm::Model
  list :comments, Comment
end

class Comment < Ohm::Model
end

What is the rationale for this design choice?

like image 604
Toby Hede Avatar asked Jan 24 '11 11:01

Toby Hede


2 Answers

Just to expand on Ariejan's answer.

  • List - ordered. Similar to an Array in Ruby. Used for queues and keeping items ordered.

  • Set - an unordered list. It behaves similar to an Array in Ruby but is optimized for faster lookups.

  • Collection - used in conjunction with reference, it provides a simple way of representing associations.

In essence, collections and references are convenience methods for dealing with associations. So this:

class Post < Ohm::Model
  attribute :title
  attribute :body
  collection :comments, Comment
end

class Comment < Ohm::Model
  attribute :body
  reference :post, Post
end

is a shortcut for the following:

class Post < Ohm::Model
  attribute :title
  attribute :body

  def comments
    Comment.find(:post_id => self.id)
  end
end

class Comment < Ohm::Model
  attribute :body
  attribute :post_id
  index :post_id

  def post=(post)
    self.post_id = post.id
  end

  def post
    Post[post_id]
  end
end

To answer you original question about the rationale for the design choice - collections and references were introduced to provide a simple api for representing associations.

like image 151
Bart Jedrocha Avatar answered Sep 30 '22 20:09

Bart Jedrocha


List - ordered list of elements. When you request the entire list, you get the items ordered the way you put them in the list.

Collection - unordered collection of elements. When you request the collection, items may appear in random order (e.g. unordered).**

In your example, comments are ordered.

** I know that random is not the same as unordered, but it does illustrate the point.

like image 23
Ariejan Avatar answered Sep 30 '22 18:09

Ariejan