Sha256: dcf5c14e8573433c302063d27d749953a8021623bf1b926214369e5dab6bc87d

Contents?: true

Size: 890 Bytes

Versions: 3

Compression:

Stored size: 890 Bytes

Contents

require 'active_support/core_ext/hash'
require 'json'

module HashSerializer
  # Serializes Ruby objects to JSON for storage in Postgres tables
  module Serializer
    # Dump the contents of hash to JSON
    #
    # Example:
    #   >> HashSerializer.dump({name: 'John'})
    #   => "{'name': 'John'}"
    #
    # @param hash [Hash]
    def self.dump(hash)
      hash.to_json
    end

    # Loads the contents of hash from JSON if hash is a String or returns the array otherwise
    #
    # Example:
    #   >> HashSerializer.load("{name: 'John'}")
    #   => {'name': 'John'}
    #
    #   >> HashSerializer.load({name: 'John'})
    #   => {'name': 'John'}
    #
    #   >> HashSerializer.load(nil)
    #   => {}
    #
    # @param hash [String, Hash]
    def self.load(hash)
      hash = JSON.parse(hash) if hash.is_a?(String)
      (hash || {}).with_indifferent_access
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
hash_serializer-0.2.0 lib/hash_serializer/serializer.rb
hash_serializer-0.1.1 lib/hash_serializer/serializer.rb
hash_serializer-0.1.0 lib/hash_serializer/serializer.rb