Use the left/right arrow keys to navigate.

Redis and Ohm

RubyConf Uruguay 2010

Simplicity

Driven Development

The complex way


class PostsController < ApplicationController

  # GET /posts/:id
  def show
    ...
  end
end

MyApp::Application.routes.draw do
  resources :posts
end

The simple way


get "/posts/:id" do
  ...
end

Rack + Rails


flash.now[:notice] = "Post successfully created"

- if flash[:notice]
  .notice!= flash[:notice]

Rack


session[:notice] = "Post successfully created"

- if session[:notice]
  .notice!= session.delete(:notice)

Difference

102 lines of code

Class level validations


validates_presence_of :surname, :if => "name.nil?"

Instance level validations


validates_presence_of :surname if name.nil?

Difference

Uncountable

More info

Superfluous DSLs

Complex tools

make you work more

Redis

and Global Variables

$global = Hash.new
$global["title"] = "hello"
$global["title"] #=> "hello"
redis = Redis.new
redis["title"] = "hello"
redis["title"] #=> "hello"
$global["user:1"] = {
  "id" => 1,
  "name" => "Albert"
}
redis.hmset("user:1",
  "id", 1,
  "name", "Albert"
)
$global["user:1:friends"] = Set.new
$global["user:1:friends"].add(2)
redis.sadd("user:1:friends", 2)

Object Oriented Keys

user = Nest.new("user")
>> user[1]
=> "user:1"
>> user[:foo][1]["bar"]
=> "user:foo:1:bar"
# Instead of
redis.sadd("user:1:friends", 2)

# you can use
user[1][:friends].sadd(2)
albert = user[1]
benoit = user[2]
albert[:friends].sadd(3)
albert[:friends].sadd(4)
albert[:friends].sadd(5)

benoit[:friends].sadd(3)
benoit[:friends].sadd(5)
benoit[:friends].sadd(6)
>> albert[:friends].sinter(benoit[:friends])
=> ["3", "5"]

Object-Hash Mapping

class User < Ohm::Model
  attribute :name

  set :friends, User
end
albert = User.create(name: "Albert")
benoit = User.create(name: "Benoit")
albert.friends << benoit
>> albert.friends.first
=> #<User:2 name="Benoit" friends=#<Set (User): ["1"]>>
>> albert.key
=> "User:1"

>> albert.friends.key
=> "User:1:friends"

Validations

def validate
  assert_present :name
end

Errors

user.name = ""
user.valid? #=> false
user.errors #=> [[:name, :not_present]]

More info

Ohm and Redis

Questions?