Class: Redis::Attrs::Scalar

Inherits:
Base
  • Object
show all
Defined in:
lib/redis-attrs/scalar.rb

Direct Known Subclasses

Boolean, Date, Float, Integer, String, Time

Instance Attribute Summary

Attributes inherited from Base

#klass, #name, #options, #type

Instance Method Summary collapse

Methods inherited from Base

#redis, #redis_key

Constructor Details

#initialize(klass, name, type, options) ⇒ Scalar

Returns a new instance of Scalar.


7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/redis-attrs/scalar.rb', line 7

def initialize(klass, name, type, options)
  super
  attr = self

  # Define the getter
  klass.send(:define_method, name) do
    value = redis.get attr.redis_key(id)
    value.nil? ? nil : attr.deserialize(value)
  end

  # Define the setter
  klass.send(:define_method, "#{name}=") do |value|
    if value.nil?
      redis.del attr.redis_key(id)
    else
      value = attr.serialize(value)
      redis.set attr.redis_key(id), value
    end
  end
end

Instance Method Details

#deserialize(value) ⇒ Object


32
33
34
# File 'lib/redis-attrs/scalar.rb', line 32

def deserialize(value)
  value
end

#serialize(value) ⇒ Object


28
29
30
# File 'lib/redis-attrs/scalar.rb', line 28

def serialize(value)
  value.to_s
end