Class: Moneta::Transforms::Escape

Inherits:
Moneta::Transform show all
Defined in:
lib/moneta/transforms/escape.rb

Overview

Encodes strings using RFC 1738 %-escaping, commonly used in URL query strings.

Examples:

transform = Moneta::Transforms::Escape.new
string = 'This "string", containing punctuation?'
transform.encode(string) # => "This%20%22string%22%2C%20containing%20punctuation%3F"

Instance Method Summary collapse

Methods inherited from Moneta::Transform

#decodable?, delegate_to, #initialize, #method_missing, #respond_to_missing?

Constructor Details

This class inherits a constructor from Moneta::Transform

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class Moneta::Transform

Instance Method Details

#decode(value) ⇒ String

Unescapes any characters %-encoded characters in the string



24
25
26
27
28
# File 'lib/moneta/transforms/escape.rb', line 24

def decode(value)
  value.gsub(/(?:%[0-9a-fA-F]{2})+/) do |match|
    [match.delete("%")].pack("H*")
  end
end

#encode(value) ⇒ String

Escapes characters in the given string except for alphanum, “-” and “_”.



14
15
16
17
18
# File 'lib/moneta/transforms/escape.rb', line 14

def encode(value)
  value.gsub(/[^a-zA-Z0-9_-]+/) do |match|
    "%#{match.unpack('H2' * match.bytesize).join('%').upcase}"
  end
end