Class: ParameterSubstitution::Encoder

Inherits:
Object
  • Object
show all
Defined in:
lib/parameter_substitution/encoder.rb

Constant Summary collapse

ENCODINGS =
{
  cgi:            "CGI encode - for html parameters",
  html:           "HTML encode - for html content",
  xml:            "XML encode",
  angle_brackets: "Content converted to a string and placed in angle brackets",
  json:           "JSON encode",
  raw:            "content is not changed",
  text:           "content is converted to a string"
}.keys

Class Method Summary collapse

Class Method Details

.encode(value, destination_encoding, source_encoding, parameter_name, inside_quotes) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/parameter_substitution/encoder.rb', line 20

def encode(value, destination_encoding, source_encoding, parameter_name, inside_quotes)
  destination_encoding.in?(ENCODINGS) or raise "unknown encoding #{destination_encoding}"
  source_encoding.in?(ENCODINGS) or raise "unknown encoding #{source_encoding}"

  result =
    if source_encoding == destination_encoding
      if destination_encoding == :json && inside_quotes
        value.to_json
      else
        value
      end
    else
      case destination_encoding
      when :cgi
        CGI.escape(value.to_s)
      when :html
        CGI.escapeHTML(value.to_s)
      when :xml
        value_for_xml(parameter_name, value)
      when :angle_brackets
        "<#{value}>"
      when :json
        value.to_json
      when :raw
        value
      when :text
        value.to_s
      else
        raise "unexepected escaping #{destination_encoding}"
      end
    end

  if destination_encoding == :json && inside_quotes
    if value.is_a?(String)
      result[1...-1]
    else
      result.to_json[1...-1]
    end
  else
    result
  end
end