Class: MetasploitDataModels::Base64Serializer

Inherits:
Object
  • Object
show all
Defined in:
lib/metasploit_data_models/base64_serializer.rb

Overview

Provides ActiveRecord 3.1x-friendly serialization for descendants of ApplicationRecord. Backwards compatible with older YAML methods and will fall back to string decoding in the worst case

Examples:

Using default default of {}

serialize :foo, MetasploitDataModels::Base64Serializer.new

Overriding default to []

serialize :bar, MetasploitDataModels::Base64Serializer.new(:default => [])

Constant Summary collapse

DEFAULT =

The default for #default

{}
LOADERS =

Deserializers for #load

  1. Base64 decoding and then unmarshalling the value.
  2. Parsing the value as YAML.
  3. The raw value.
[
    lambda { |serialized|
      marshaled = serialized.unpack('m').first
      # Load the unpacked Marshal object first
      Marshal.load(marshaled)
    },
    lambda { |serialized|
      # Support legacy YAML encoding for existing data
      YAML.load(serialized)
    },
    lambda { |serialized|
      # Fall back to string decoding
      serialized
    }
]

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes = {}) ⇒ Base64Serializer

Returns a new instance of Base64Serializer.

Parameters:

  • attributes (Hash) (defaults to: {})

    attributes

Options Hash (attributes):

  • :default (Object) — default: {}

    Value to use for #default.



65
66
67
68
69
# File 'lib/metasploit_data_models/base64_serializer.rb', line 65

def initialize(attributes={})
  attributes.assert_valid_keys(:default)

  @default = attributes.fetch(:default, DEFAULT)
end

Instance Attribute Details

#defaultObject

Creates a duplicate of default value

Returns:



45
46
47
# File 'lib/metasploit_data_models/base64_serializer.rb', line 45

def default
  @default.dup
end

Instance Method Details

#dump(value) ⇒ String

Serializes the value by marshalling the value and then base64 encodes the marshaled value.

Parameters:

  • value (Object)

    value to serialize

Returns:

  • (String)


55
56
57
58
59
60
61
# File 'lib/metasploit_data_models/base64_serializer.rb', line 55

def dump(value)
  # Always store data back in the Marshal format
  marshalled = Marshal.dump(value)
  base64_encoded = [ marshalled ].pack('m')

  base64_encoded
end

#load(value) ⇒ Object

Deserializes the value by either

  1. Base64 decoding and then unmarshalling the value.
  2. Parsing the value as YAML.
  3. Returns the raw value.

Parameters:

  • value (String)

    serialized value

Returns:

  • (Object)

See Also:



80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/metasploit_data_models/base64_serializer.rb', line 80

def load(value)
  loaded = nil

  if value.blank?
    loaded = default
  else
    LOADERS.each do |loader|
      begin
        loaded = loader.call(value)
      rescue
        next
      else
        break
      end
    end
  end

  loaded
end