Class: EacRubyUtils::Yaml

Inherits:
Object show all
Defined in:
lib/eac_ruby_utils/yaml.rb

Overview

A safe YAML loader/dumper with common types included.

Defined Under Namespace

Classes: Sanitizer

Constant Summary collapse

DEFAULT_PERMITTED_CLASSES =
[::Array, ::Date, ::DateTime, ::FalseClass, ::Hash, ::NilClass,
::Numeric, ::String, ::Symbol, ::Time, ::TrueClass].freeze

Class Method Summary collapse

Class Method Details

.dump(object) ⇒ Object


13
14
15
# File 'lib/eac_ruby_utils/yaml.rb', line 13

def dump(object)
  ::YAML.dump(sanitize(object))
end

.dump_file(path, object) ⇒ Object


17
18
19
# File 'lib/eac_ruby_utils/yaml.rb', line 17

def dump_file(path, object)
  ::File.write(path.to_s, dump(object))
end

.load(string) ⇒ Object


21
22
23
# File 'lib/eac_ruby_utils/yaml.rb', line 21

def load(string)
  ::YAML.safe_load(string, permitted_classes)
end

.load_file(path) ⇒ Object


25
26
27
# File 'lib/eac_ruby_utils/yaml.rb', line 25

def load_file(path)
  load(::File.read(path.to_s))
end

.permitted_classesObject


29
30
31
# File 'lib/eac_ruby_utils/yaml.rb', line 29

def permitted_classes
  DEFAULT_PERMITTED_CLASSES
end

.sanitize(object) ⇒ Object


33
34
35
# File 'lib/eac_ruby_utils/yaml.rb', line 33

def sanitize(object)
  Sanitizer.new(object).result
end

.yaml?(object) ⇒ Boolean

Returns:


37
38
39
40
41
42
43
44
45
# File 'lib/eac_ruby_utils/yaml.rb', line 37

def yaml?(object)
  return false unless object.is_a?(::String)
  return false unless object.start_with?('---')

  load(object)
  true
rescue ::Psych::SyntaxError
  false
end