Class: HashSerializer

Inherits:
Object
  • Object
show all
Defined in:
app/serializers/hash_serializer.rb

Overview

Only use this with a json or jsonb back end column

Class Method Summary collapse

Class Method Details

.dump(hash) ⇒ Object



3
4
5
# File 'app/serializers/hash_serializer.rb', line 3

def self.dump(hash)
  hash
end

.load(hash_raw) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'app/serializers/hash_serializer.rb', line 7

def self.load(hash_raw)
  hash = nil
  if hash_raw.is_a?(String)
    hash_raw.strip

    # Try JSON first
    begin
      hash = JSON.parse(hash_raw, symbolize_names: true)
    rescue JSON::ParserError
      # Fall back to YAML
    end

    if hash.nil?
      # Try YAML (handles Ruby-style hash), this can come from an input form
      begin
        hash = YAML.safe_load(hash_raw, permitted_classes: [Symbol]) || {}
      rescue Psych::SyntaxError
        # nope
      end
    end
  elsif hash_raw.is_a?(Hash) || hash_raw.is_a?(Array)
    hash = hash_raw
  end

  # Default
  hash ||= {}
  # You might have an array which does not respond to with indifferent access
  if hash.is_a?(Array)
    hash.map { |v| v.respond_to?(:with_indifferent_access) ? v.with_indifferent_access : v }
  elsif hash.respond_to?(:with_indifferent_access)
    hash.with_indifferent_access
  else
    hash
  end
end