Module: RedisModelExtension::ValueTransform

Defined in:
lib/redis-model-extension/value_transform.rb

Instance Method Summary collapse

Instance Method Details

#value_parse(value, type) ⇒ Object

convert value from redis into valid format in ruby



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/redis-model-extension/value_transform.rb', line 33

def value_parse value, type
  return nil if value.nil? || value.to_s.size == 0
  case type
  when :integer then value.to_i
  when :autoincrement then value.to_i
  when :string then value.to_s
  when :float then value.to_f
  when :bool then value.to_s.to_bool
  when :symbol then value.to_s.to_sym
  when :array then value.is_a?(String) ? JSON.parse(value) : value
  when :hash then value.is_a?(String) ? Hashr.new(JSON.parse(value)) : Hashr.new(value)
  when :time then value.is_a?(String) ? Time.parse(value) : value
  when :date then value.is_a?(String) ? Date.parse(value) : value
  else value
  end
end

#value_to_redis(name, value) ⇒ Object

choose right type of value and then transform it for redis



6
7
8
9
10
11
12
# File 'lib/redis-model-extension/value_transform.rb', line 6

def value_to_redis name, value
  if redis_fields_config.has_key?(name)
    value_transform value, redis_fields_config[name]
  else
    value
  end
end

#value_transform(value, type) ⇒ Object

convert value for valid format which can be saved in redis



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/redis-model-extension/value_transform.rb', line 15

def value_transform value, type
  return nil if value.nil? || value.to_s.size == 0
  case type
  when :integer then value.to_i
  when :autoincrement then value.to_i
  when :string then value.to_s
  when :float then value.to_f
  when :bool then value.to_s
  when :symbol then value.to_s
  when :array then value.to_json
  when :hash then value.to_json
  when :time then Time.parse(value.to_s).strftime("%Y.%m.%d %H:%M:%S")
  when :date then Date.parse(value.to_s).strftime("%Y-%m-%d")
  else value
  end
end