Class: RightSupport::Net::StringEncoder

Inherits:
Object
  • Object
show all
Defined in:
lib/right_support/net/string_encoder.rb

Overview

A tool that encodes (binary or ASCII) strings into 7-bit ASCII using one or more encoding algorithms which are applied sequentially. The order of algorithms is reversed on decode, naturally!

This class is designed to be used with network protocols implemented on top of HTTP, where binary data needs to be encapsulated in URL query strings, request bodies or other textual payloads. Sometimes multiple encodings are necessary in order to prevent unnecessary expansion of the encoded text.

Ruby 1.9 and Character Encodings

Input Strings

The #encode and #decode methods accept strings with any encoding, and do not perform any conversion or coercion between encodings. Strings are passed unmodified to the underlying encoding libraries.

Output Strings

The #encode method always returns strings with an encoding of US-ASCII, because the output of all encodings is guaranteed to be 7-bit ASCII.

The #decode method always returns strings with an encoding of ASCII-8BIT (aka BINARY) because there is no way to determine the correct encoding. The caller of #decode should use String#force_encoding to coerce the output value to an appropriate encoding before displaying or manipulating the output.

Constant Summary collapse

ENCODINGS =
[:base64, :url]

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ StringEncoder

Create a new instance.

Parameters

*encodings

list of Symbols representing an ordered sequence of encodings



64
65
66
67
68
69
70
71
# File 'lib/right_support/net/string_encoder.rb', line 64

def initialize(*args)
  args = args.flatten
  args.each do |enc|
    raise ArgumentError, "Unknown encoding #{enc}" unless ENCODINGS.include?(enc)
  end

  @encodings = args
end

Instance Method Details

#decode(value) ⇒ Object

Decode a binary or textual string.

Parameters

value(String)

the value to be decoded

Return

The decoded string value



102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/right_support/net/string_encoder.rb', line 102

def decode(value)
  @encodings.reverse.each do |enc|
    case enc
      when :base64
        value = Base64.decode64(value)
      when :url
        value = CGI.unescape(value)
    end
  end

  value.force_encoding(Encoding::ASCII_8BIT) if value.respond_to?(:force_encoding)
  value
end

#encode(value) ⇒ Object

Encode a binary or textual string.

Parameters

value(String)

the value to be encoded

Return

The encoded value, with all encodings applied.



81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/right_support/net/string_encoder.rb', line 81

def encode(value)
  @encodings.each do |enc|
    case enc
      when :base64
        value = Base64.encode64(value)
      when :url
        value = CGI.escape(value)
    end
  end

  value
end