Class: NestedHstore::Serializer
- Inherits:
-
Object
- Object
- NestedHstore::Serializer
- Defined in:
- lib/nested_hstore/serializer.rb
Instance Method Summary collapse
- #deserialize(hash) ⇒ Object
-
#initialize ⇒ Serializer
constructor
A new instance of Serializer.
- #serialize(value) ⇒ Object
Constructor Details
#initialize ⇒ Serializer
Returns a new instance of Serializer.
4 5 6 7 8 9 10 11 12 13 14 15 |
# File 'lib/nested_hstore/serializer.rb', line 4 def initialize @type_key = '__TYPE__' @types_map = { array: '__ARRAY__', float: '__FLOAT__', hash: '__HASH__', integer: '__INTEGER__', string: '__STRING__' } @types_map_inverted = @types_map.invert @value_key = '__VALUE__' end |
Instance Method Details
#deserialize(hash) ⇒ Object
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
# File 'lib/nested_hstore/serializer.rb', line 40 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 :hash hash.each do |k, v| hash[k] = decode_json_if_json(v) end hash when :integer hash[@value_key].to_i when :string hash[@value_key] end deserialized end |
#serialize(value) ⇒ Object
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/nested_hstore/serializer.rb', line 17 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 |