Module: Philiprehberger::SafeYaml::Loader
- Defined in:
- lib/philiprehberger/safe_yaml/loader.rb
Overview
Wraps YAML.safe_load with safe defaults and size limits.
Class Method Summary collapse
-
.deep_merge(base, overlay) ⇒ Hash
Deep merges two hashes, with the overlay taking precedence.
-
.dump(data, permitted_classes: []) ⇒ String
Safely dumps data to a YAML string with type validation.
-
.dump_file(data, path, permitted_classes: []) ⇒ String
Safely dumps data to a YAML file with type validation.
-
.load(string, permitted_classes: [], max_aliases: 0, max_size: nil) ⇒ Object
Safely loads a YAML string with restricted types.
-
.load_file(path, **opts) ⇒ Object
Safely loads a YAML file with restricted types.
-
.sanitize(string) ⇒ String
Sanitizes a YAML string by stripping full-line comments and normalizing whitespace.
Class Method Details
.deep_merge(base, overlay) ⇒ Hash
Deep merges two hashes, with the overlay taking precedence.
89 90 91 92 93 94 95 96 97 |
# File 'lib/philiprehberger/safe_yaml/loader.rb', line 89 def self.deep_merge(base, ) base.merge() do |_key, old_val, new_val| if old_val.is_a?(Hash) && new_val.is_a?(Hash) deep_merge(old_val, new_val) else new_val end end end |
.dump(data, permitted_classes: []) ⇒ String
Safely dumps data to a YAML string with type validation.
105 106 107 108 |
# File 'lib/philiprehberger/safe_yaml/loader.rb', line 105 def self.dump(data, permitted_classes: []) validate_dumpable!(data, permitted_classes) YAML.dump(data) end |
.dump_file(data, path, permitted_classes: []) ⇒ String
Safely dumps data to a YAML file with type validation.
117 118 119 120 121 |
# File 'lib/philiprehberger/safe_yaml/loader.rb', line 117 def self.dump_file(data, path, permitted_classes: []) content = dump(data, permitted_classes: permitted_classes) File.write(path, content) content end |
.load(string, permitted_classes: [], max_aliases: 0, max_size: nil) ⇒ Object
Safely loads a YAML string with restricted types.
20 21 22 23 24 25 26 27 28 29 30 |
# File 'lib/philiprehberger/safe_yaml/loader.rb', line 20 def self.load(string, permitted_classes: [], max_aliases: 0, max_size: nil) validate_size!(string, max_size) validate_alias_count!(string, max_aliases) if max_aliases.positive? YAML.safe_load( string, permitted_classes: permitted_classes, permitted_symbols: [], aliases: max_aliases.positive? ) end |
.load_file(path, **opts) ⇒ Object
Safely loads a YAML file with restricted types.
39 40 41 42 |
# File 'lib/philiprehberger/safe_yaml/loader.rb', line 39 def self.load_file(path, **opts) content = File.read(path) load(content, **opts) end |
.sanitize(string) ⇒ String
Sanitizes a YAML string by stripping full-line comments and normalizing whitespace.
77 78 79 80 81 82 |
# File 'lib/philiprehberger/safe_yaml/loader.rb', line 77 def self.sanitize(string) lines = string.each_line.grep_v(/\A\s*#/) cleaned = lines.join.gsub(/[^\S\n]+$/, '') YAML.safe_load(cleaned) # validate syntax cleaned end |