Sha256: 02107bbca0087a459c9f9af45b1002b041ea4ff0140ce7295de99e6951220c4e

Contents?: true

Size: 1.66 KB

Versions: 2

Compression:

Stored size: 1.66 KB

Contents

# -*- encoding : utf-8 -*-
module RedisModelExtension
  module ValueTransform

    # choose right type of value and then transform it for redis
    def value_to_redis name, value
      if redis_fields_config.has_key?(name)
        value_transform value, redis_fields_config[name]
      else
        value
      end
    end

    # convert value for valid format which can be saved in redis
    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

    # convert value from redis into valid format in ruby
    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

  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
redis-model-extension-0.4.2 lib/redis-model-extension/value_transform.rb
redis-model-extension-0.4.1 lib/redis-model-extension/value_transform.rb