Class: Sendgrid::Parse::EncodableHash

Inherits:
SimpleDelegator
  • Object
show all
Defined in:
lib/sendgrid-parse/encodable_hash.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(component) ⇒ EncodableHash

Returns a new instance of EncodableHash.



16
17
18
19
20
21
22
23
24
25
26
# File 'lib/sendgrid-parse/encodable_hash.rb', line 16

def initialize(component)
  # Symbolize keys
  if component.respond_to? :symbolize_keys
    component = component.symbolize_keys
  else
    component.keys.each { |key| component[(key.to_sym rescue key) || key] = component.delete(key) }
  end

  raise 'Missing required key :charsets for encoding.' unless component.has_key?(:charsets)
  super
end

Instance Attribute Details

#componentObject

Returns the value of attribute component.



10
11
12
# File 'lib/sendgrid-parse/encodable_hash.rb', line 10

def component
  @component
end

Instance Method Details

#classObject



12
13
14
# File 'lib/sendgrid-parse/encodable_hash.rb', line 12

def class
  __getobj__.class
end

#encode(to_encoding, ignore = []) ⇒ Object



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
# File 'lib/sendgrid-parse/encodable_hash.rb', line 28

def encode(to_encoding, ignore=[])
  _test_encoding(to_encoding)

  component = __getobj__.dup
  ignore.each { |e| component.delete(e) if component.has_key?(e)}

  # Parse and symbolize charsets dictionary
  charsets = JSON.parse(component[:charsets])
  charsets.keys.each { |key| charsets[(key.to_sym rescue key) || key] = charsets.delete(key) }

  # Set and/or change all fields according to charsets
  component.each do |key, value|
    if charsets.has_key?(key)
      from_encoding = charsets[key]
      transcoded_value = _encode(component[key], from_encoding, to_encoding) rescue nil

      if transcoded_value
        component[key] = transcoded_value
        charsets[key] = to_encoding
      end
    end
  end

  component[:charsets] = charsets.to_json
  component
end

#encode!(to_encoding, ignore = []) ⇒ Object



55
56
57
# File 'lib/sendgrid-parse/encodable_hash.rb', line 55

def encode!(to_encoding, ignore=[])
  __setobj__ encode(to_encoding, ignore)
end