Class: NestedHstore::Serializer

Inherits:
Object
  • Object
show all
Defined in:
lib/nested_hstore/serializer.rb

Instance Method Summary collapse

Constructor Details

#initializeSerializer

Returns a new instance of Serializer.



4
5
6
7
8
9
10
11
12
13
14
# File 'lib/nested_hstore/serializer.rb', line 4

def initialize
  @type_key = '__TYPE__'
  @types_map = {
    array: '__ARRAY__',
    float: '__FLOAT__',
    integer: '__INTEGER__',
    string: '__STRING__'
  }
  @types_map_inverted = @types_map.invert
  @value_key = '__VALUE__'
end

Instance Method Details

#deserialize(hash) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/nested_hstore/serializer.rb', line 39

def deserialize(hash)
  return nil if hash.nil?
  raise 'Hstore value should be a hash' unless hash.is_a?(Hash)
  type_value = hash.delete(@type_key)
  type = @types_map_inverted[type_value]
  deserialized = case type
    when :array
      hash.values.map { |v| decode_json_if_json(v) }
    when :float
      hash[@value_key].to_f
    when :integer
      hash[@value_key].to_i
    when :string
      hash[@value_key]
    else
      hash.each do |k, v|
        hash[k] = decode_json_if_json(v)
      end
      hash
  end
  deserialized
end

#serialize(value) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/nested_hstore/serializer.rb', line 16

def serialize(value)
  return nil if value.nil?
  if value.is_a?(Array)
    type = :array
    hash = array_to_hash(value)
  elsif value.is_a?(Float)
    type = :float
    hash = { @value_key => value }
  elsif value.is_a?(Hash)
    type = :hash
    hash = standardize_value(value)
  elsif value.is_a?(Integer)
    type = :integer
    hash = { @value_key => value }
  elsif value.is_a?(String)
    type = :string
    hash = { @value_key => value }
  else
    raise "Unsupported hstore type: #{value.class}"
  end
  hash_to_hstore(type, hash)
end