Class: Coaster::SafeYamlSerializer

Inherits:
Object
  • Object
show all
Defined in:
lib/coaster/safe_yaml_serializer.rb

Class Method Summary collapse

Class Method Details

._load_hash(yaml) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/coaster/safe_yaml_serializer.rb', line 11

def _load_hash(yaml)
  return {} if yaml.nil?
  return yaml unless yaml.is_a?(String) && yaml.start_with?("---")

  begin
    YAML.safe_load(yaml, permitted_classes: [Date, Time], aliases: true) || {}
  rescue Psych::DisallowedClass => e
    if YAML.respond_to?(:unsafe_load)
      YAML.unsafe_load(yaml) || {}
    else
      YAML.load(yaml) || {}
    end
  end
end

.dump(obj) ⇒ Object



6
7
8
9
# File 'lib/coaster/safe_yaml_serializer.rb', line 6

def dump(obj)
  return if obj.nil?
  YAML.dump(JSON.load(obj.to_json))
end

.load(yaml) ⇒ HashWithIndifferentAccess

Returns:

  • (HashWithIndifferentAccess)


27
28
29
30
31
# File 'lib/coaster/safe_yaml_serializer.rb', line 27

def load(yaml)
  obj = _load_hash(yaml)
  obj = obj.with_indifferent_access if obj.is_a?(Hash)
  obj
end