Sha256: 0f62b4c6d82211a4757b0790604be66e8624ee1e0da5dd51d33f9dc3a0ee0481

Contents?: true

Size: 1.05 KB

Versions: 5

Compression:

Stored size: 1.05 KB

Contents

# Serializable provides functionality around serialization to the classes that
# extend it. This includes a class method to deserialize a string and create an
# instance of the class.

module Serializable
  # @param str [String] the serialized object string
  # @return [Object] the object represented by the serialized string
  # Note: this method assumes the calling class provides the following methods:
  #   - deserialization_regex
  #       a regex for the string which includes named parameters for the
  #       different initializer arguments
  #   - deserialization_expectation
  #       a string for what was expected, if the regex does not match
  def deserialize(str)
    match = str.match(deserialization_regex)

    unless match
      raise SerializationError,
            "Expected \"#{deserialization_expectation}\""
    end

    args = match.names.
           map { |name| { name.to_sym => match[name.to_sym] } }.
           reduce(:merge).
           select { |_, v| !v.nil? }

    new(args)
  end

  class SerializationError < StandardError
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
friends-0.0.6 lib/friends/serializable.rb
friends-0.0.5 lib/friends/serializable.rb
friends-0.0.4 lib/friends/serializable.rb
friends-0.0.3 lib/friends/serializable.rb
friends-0.0.2 lib/friends/serializable.rb