Class: Smooth::Backends::Redis

Inherits:
Base
  • Object
show all
Defined in:
lib/smooth/backends/redis.rb

Direct Known Subclasses

RedisNamespace

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#query, #records

Constructor Details

#initialize(options = {}) ⇒ Redis

Returns a new instance of Redis.



7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/smooth/backends/redis.rb', line 7

def initialize options={}
  redis = ::Redis.new(options[:redis_options] || {})

  @namespace        = options[:namespace]
  @priority         = options[:priority] || 0

  if options[:use_redis_namespace]
    @connection       = ::Redis::Namespace.new(Smooth.namespace, redis: redis)
  else
    @connection = redis
  end
end

Instance Attribute Details

#connectionObject (readonly)

Returns the value of attribute connection.



4
5
6
# File 'lib/smooth/backends/redis.rb', line 4

def connection
  @connection
end

#namespaceObject (readonly)

Returns the value of attribute namespace.



4
5
6
# File 'lib/smooth/backends/redis.rb', line 4

def namespace
  @namespace
end

Instance Method Details

#create(attributes = {}) ⇒ Object



20
21
22
23
24
25
26
# File 'lib/smooth/backends/redis.rb', line 20

def create attributes={}
  attributes.symbolize_keys!
  attributes[:created_at] = attributes[:updated_at] = touch
  attributes[:id] = increment_id
  connection.hset("#{ namespace }:records", attributes[:id], JSON.generate(attributes))
  attributes
end

#destroy(id) ⇒ Object



38
39
40
# File 'lib/smooth/backends/redis.rb', line 38

def destroy id
  !!(connection.hdel("#{ namespace }:records", id.to_s))
end

#indexObject



42
43
44
45
46
# File 'lib/smooth/backends/redis.rb', line 42

def index
  records = connection.hvals("#{ namespace }:records")
  records.map! {|r| JSON.parse(r) }
  records
end

#show(id) ⇒ Object



48
49
50
51
52
53
# File 'lib/smooth/backends/redis.rb', line 48

def show id
  record = connection.hget("#{ namespace }:records", id)
  parsed = JSON.parse(record)
  parsed && parsed.symbolize_keys!
  parsed
end

#update(attributes = {}) ⇒ Object



28
29
30
31
32
33
34
35
36
# File 'lib/smooth/backends/redis.rb', line 28

def update attributes={}
  attributes.symbolize_keys!
  if record = show(attributes[:id])
    record.merge!(attributes)
    record[:updated_at] = touch
    connection.hset("#{ namespace }:records", attributes[:id], JSON.generate(record))
    record
  end
end