Class: Rodbot::Serializer

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

Overview

Simple yet safe Hash to String serializer

Keep in mind that hash keys will always be deserialized as strings!

Example:

hash = { 'foo' => 'bar' }
string = Serializer.new(hash).string
# => "data:application/json;base64,eyJmb28iOiJiYXIifQ=="
hash = Serializer.new(string).hash
# => { 'foo' => 'bar' }

Constant Summary collapse

PRELUDE =

Prelude string for serialized hash

'data:application/json;base64,'

Instance Method Summary collapse

Constructor Details

#initialize(object) ⇒ Serializer

Returns a new instance of Serializer.



25
26
27
28
29
30
31
# File 'lib/rodbot/serializer.rb', line 25

def initialize(object)
  case object
    when Hash then @hash = object
    when String then @string = object
    else fail ArgumentError, "must be either Hash or String"
  end
end

Instance Method Details

#deserializable?Boolean

Returns whether the object passed with new is deserializable.

Returns:

  • (Boolean)

    whether the object passed with new is deserializable



60
61
62
# File 'lib/rodbot/serializer.rb', line 60

def deserializable?
  @string && @string.match?(/\A#{PRELUDE}/)
end

#hashHash

Returns String deserialized to Hash.

Returns:

  • (Hash)

    String deserialized to Hash

Raises:

  • (RuntimeError)

    when deserialization fails



43
44
45
46
47
48
49
50
51
52
# File 'lib/rodbot/serializer.rb', line 43

def hash
  @hash ||= begin
    fail "object is not deserializable" unless deserializable?
    JSON.load(Base64.strict_decode64(@string.delete_prefix(PRELUDE)))
  end
rescue ArgumentError
  raise "invalid Base64"
rescue JSON::ParserError
  raise "invalid JSON"
end

#serializable?Boolean

Returns whether the object passed with new is serializable.

Returns:

  • (Boolean)

    whether the object passed with new is serializable



55
56
57
# File 'lib/rodbot/serializer.rb', line 55

def serializable?
  !!@hash
end

#stringString

Returns Hash serialized to String.

Returns:

  • (String)

    Hash serialized to String



34
35
36
37
38
39
# File 'lib/rodbot/serializer.rb', line 34

def string
  @string ||= begin
    fail "object is not serializable" unless serializable?
    @hash.to_json.then { PRELUDE + Base64.strict_encode64(_1) }
  end
end