Skip to content

Instantly share code, notes, and snippets.

@yash-doshi
Last active April 22, 2018 12:37
Show Gist options
  • Save yash-doshi/dc5863e7a44dcbb500cf88191a901b36 to your computer and use it in GitHub Desktop.
Save yash-doshi/dc5863e7a44dcbb500cf88191a901b36 to your computer and use it in GitHub Desktop.
# Serializing Symbols for ActiveJobs
# For the context of this gist, serialization of symbols simply means deconstruction of symbols into serializable hash.
# include in any ActiveJob where you need to pass symbol(s) in arguments
# Deconstructs any symbol into a standard and discernible Hash, which can be serialized
# Example- :apples => { _serializing_datatype: 'Symbol', _value: 'apples' }
module SymbolSerializer
extend ActiveSupport::Concern
included do
before_enqueue :serialize_symbol_in_arguments
before_perform :deserialize_symbol_in_arguments
# Looks for symbols in every argument of the job
def serialize_symbol_in_arguments
self.arguments.each_with_index do |element, index|
self.arguments[index] = element_serializer(element)
end
end
# Looks for serialized symbols in every argument of the job
def deserialize_symbol_in_arguments
self.arguments.each_with_index do |element, index|
self.arguments[index] = element_deserializer(element)
end
end
# recursively parses any element passed, looking for symbols
def element_serializer(element)
return nil if element.nil?
if element.instance_of? Symbol
element = symbol_serializer(element)
elsif element.is_a? Hash
element.keys.each do |key|
value = element[key]
element[key] = element_serializer(value)
end
elsif element.is_a? Array
element.each_with_index do |value, index|
element[index] = element_serializer(value)
end
end
element
end
# recursively parses any element passed, looking for serialized symbols
def element_deserializer(element)
return nil if element.nil?
if is_a_serialized_symbol?(element)
element = symbol_deserializer(element)
elsif element.is_a? Hash
element.keys.each do |key|
value = element[key]
element[key] = element_deserializer(value)
end
elsif element.is_a? Array
element.each_with_index do |value, index|
element[index] = element_deserializer(value)
end
end
element
end
# takes a symbol, returns a deconstructed serialized symbol
def symbol_serializer(symbol)
return symbol unless symbol.class == Symbol
{
_serializing_datatype: Symbol.name,
_value: symbol.to_s
}
end
# takes a serialized symbol, returns a reconstructed symbol
def symbol_deserializer(serialized_symbol)
return serialized_symbol unless is_a_serialized_symbol?(serialized_symbol)
serialized_symbol[:_value].intern
end
# Checks whether a hash(like) is actually a deconstrcuted serialized symbol
def is_a_serialized_symbol?(hash)
hash.is_a?(Hash) &&
hash[:_serializing_datatype].present? &&
hash[:_serializing_datatype] == Symbol.name
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment