Sha256: 7f8ba55ed3ec8a6a6bb4e7f0ba8b6042510bb6a472165a3dd9eb44cb64311870

Contents?: true

Size: 1005 Bytes

Versions: 1

Compression:

Stored size: 1005 Bytes

Contents

# encoding: utf-8
require 'base64'
require 'multi_json'

module Dragonfly
  module Serializer

    # Exceptions
    class BadString < RuntimeError; end

    extend self # So we can do Serializer.b64_encode, etc.

    def b64_encode(string)
      Base64.encode64(string).tr("\n=",'')
    end

    def b64_decode(string)
      padding_length = string.length % 4
      Base64.decode64(string + '=' * padding_length)
    end

    def marshal_encode(object)
      b64_encode(Marshal.dump(object))
    end

    def marshal_decode(string)
      Marshal.load(b64_decode(string))
    rescue TypeError, ArgumentError => e
      raise BadString, "couldn't decode #{string} - got #{e}"
    end

    def json_encode(object)
      b64_encode(MultiJson.encode(object))
    end

    def json_decode(string, opts={})
      MultiJson.decode(b64_decode(string), :symbolize_keys => opts[:symbolize_keys])
    rescue MultiJson::DecodeError => e
      raise BadString, "couldn't decode #{string} - got #{e}"
    end

  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
dragonfly-0.9.13 lib/dragonfly/serializer.rb