Module: SnakyHash::Serializer

Defined in:
lib/snaky_hash/serializer.rb

Overview

Provides JSON serialization and deserialization capabilities with extensible value transformation

Examples:

Basic usage

class MyHash < Hashie::Mash
  extend SnakyHash::Serializer
end
hash = MyHash.load('{"key": "value"}')
hash.dump #=> '{"key":"value"}'

Defined Under Namespace

Modules: BackportedInstanceMethods, Modulizer

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extended(base) ⇒ void

This method returns an undefined value.

Extends the base class with serialization capabilities

Parameters:

  • base (Class)

    the class being extended



21
22
23
24
25
26
27
28
29
30
# File 'lib/snaky_hash/serializer.rb', line 21

def extended(base)
  extended_module = Modulizer.to_extended_mod
  base.extend(extended_module)
  # :nocov:
  # This will be run in CI on Ruby 2.3, but we only collect coverage from current Ruby
  unless base.instance_methods.include?(:transform_values)
    base.include(BackportedInstanceMethods)
  end
  # :nocov:
end

Instance Method Details

#dump(obj) ⇒ String

Serializes a hash object to JSON

Parameters:

  • obj (Hash)

    the hash to serialize

Returns:

  • (String)

    JSON string representation of the hash



37
38
39
40
# File 'lib/snaky_hash/serializer.rb', line 37

def dump(obj)
  hash = dump_hash(obj)
  hash.to_json
end

#load(raw_hash) ⇒ Hash

Deserializes a JSON string into a hash object

Parameters:

  • raw_hash (String, nil)

    JSON string to deserialize

Returns:

  • (Hash)

    deserialized hash object



46
47
48
49
50
# File 'lib/snaky_hash/serializer.rb', line 46

def load(raw_hash)
  hash = JSON.parse(presence(raw_hash) || "{}")
  hash = load_value(new(hash))
  new(hash)
end