Module: Puppet::Util::Yaml

Defined in:
lib/puppet/util/yaml.rb

Defined Under Namespace

Classes: YamlLoadError

Constant Summary collapse

YamlLoadExceptions =
[::StandardError, ::Psych::Exception]

Class Method Summary collapse

Class Method Details

.dump(structure, filename) ⇒ Object


67
68
69
70
71
# File 'lib/puppet/util/yaml.rb', line 67

def self.dump(structure, filename)
  Puppet::Util.replace_file(filename, 0660) do |fh|
    YAML.dump(structure, fh)
  end
end

.load_file(filename, default_value = false, strip_classes = false) ⇒ Object

Deprecated.

Use #safe_load_file instead.


46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/puppet/util/yaml.rb', line 46

def self.load_file(filename, default_value = false, strip_classes = false)
  Puppet.deprecation_warning(_("Puppet::Util::Yaml.load_file is deprecated. Use safe_load_file instead."))

  if(strip_classes) then
    data = YAML::parse_file(filename)
    data.root.each do |o|
      if o.respond_to?(:tag=) and
         o.tag != nil and
         o.tag.start_with?("!ruby")
        o.tag = nil
      end
    end
    data.to_ruby || default_value
  else
    yaml = YAML.load_file(filename)
    yaml || default_value
  end
rescue *YamlLoadExceptions => detail
  raise YamlLoadError.new(detail.message, detail)
end

.safe_load(yaml, allowed_classes = [], filename = nil) ⇒ Object

Safely load the content as YAML. By default only the following classes can be deserialized:

  • TrueClass

  • FalseClass

  • NilClass

  • Numeric

  • String

  • Array

  • Hash

Attempting to deserialize other classes will raise an YamlLoadError exception unless they are specified in the array of allowed_classes.

Raises:

  • (YamlLoadException)

    If deserialization fails.


26
27
28
29
30
31
32
33
34
35
# File 'lib/puppet/util/yaml.rb', line 26

def self.safe_load(yaml, allowed_classes = [], filename = nil)
  data = YAML.safe_load(yaml, allowed_classes, [], true, filename)
  data = false if data.nil?
  data
rescue ::Psych::DisallowedClass => detail
  path = filename ? "(#{filename})" : "(<unknown>)"
  raise YamlLoadError.new("#{path}: #{detail.message}", detail)
rescue *YamlLoadExceptions => detail
  raise YamlLoadError.new(detail.message, detail)
end

.safe_load_file(filename, allowed_classes = []) ⇒ Object

Safely load the content from a file as YAML.

See Also:


40
41
42
43
# File 'lib/puppet/util/yaml.rb', line 40

def self.safe_load_file(filename, allowed_classes = [])
  yaml = Puppet::FileSystem.read(filename, :encoding => 'bom|utf-8')
  safe_load(yaml, allowed_classes, filename)
end