tags:

views:

110

answers:

2

Greetings,

I want to store some data in a redis db and don't know which way I should go. The data is equivalent to something like an address with the variables name, street and number. They will be stored under the lower cased name as key, there won't be doublets.

Now, should I save it as a list or should I serialize the hash ({:name => 'foo', :street => 'bar', :number => 'baz'} for example) with JSON/Marshall and simply store that?

Regards

Tobias

A: 

Using an encoded json object is a pretty good idea. You can see some examples in hurl — check out how the models are saved: http://github.com/defunkt/hurl/blob/master/models/model.rb

Redis hashes are nice too, especially if you need atomic operations on hash values.

kneath
A: 

Also you can use something like Nest to help you DRY up your keys:

addresses = Nest.new("Address", Redis.new)

this_address = addresses[1]
# => "Address:1"

this_address.hset(:name, "foo")
this_address.hset(:street, "bar")

this_address.hgetall
# => {"name" => "foo", "street" => "bar"}

If you need something more advanced, there's Ohm, which maps Ruby classes to Redis:

class Address < Ohm::Model
  attribute :name
  attribute :street
  attribute :number
end

# Create
Address.create(:name => "foo", :street => "bar")

# Find by ID
Address[1]

# Find all addresses with name "foo"
class Address < Ohm::Model
  attribute :name
  attribute :street
  attribute :number

  index :name
end

Address.find(:name => "foo")
# => Array-like with all the Address objects
djanowski