Class: Rodbot::Serializer
- Inherits:
-
Object
- Object
- Rodbot::Serializer
- Defined in:
- lib/rodbot/serializer.rb
Overview
Constant Summary collapse
- PRELUDE =
Prelude string for serialized hash
'data:application/json;base64,'
Instance Method Summary collapse
-
#deserializable? ⇒ Boolean
Whether the object passed with
new
is deserializable. -
#hash ⇒ Hash
String deserialized to Hash.
-
#initialize(object) ⇒ Serializer
constructor
A new instance of Serializer.
-
#serializable? ⇒ Boolean
Whether the object passed with
new
is serializable. -
#string ⇒ String
Hash serialized to String.
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.
60 61 62 |
# File 'lib/rodbot/serializer.rb', line 60 def deserializable? @string && @string.match?(/\A#{PRELUDE}/) end |
#hash ⇒ Hash
Returns String deserialized to Hash.
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.
55 56 57 |
# File 'lib/rodbot/serializer.rb', line 55 def serializable? !!@hash end |
#string ⇒ String
Returns 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 |