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 =
[ActiveSupport::TimeWithZone, ActiveSupport::TimeZone,
::Array, ::Date, ::DateTime, ::FalseClass, ::Hash, ::NilClass,
::Numeric, ::String, ::Symbol, ::Time, ::TrueClass].freeze

Class Method Summary collapse

Class Method Details

.dump(object) ⇒ Object



15
16
17
# File 'lib/eac_ruby_utils/yaml.rb', line 15

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

.dump_file(path, object) ⇒ Object



19
20
21
# File 'lib/eac_ruby_utils/yaml.rb', line 19

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

.load(string) ⇒ Object



23
24
25
# File 'lib/eac_ruby_utils/yaml.rb', line 23

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

.load_file(path) ⇒ Object



27
28
29
# File 'lib/eac_ruby_utils/yaml.rb', line 27

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

.permitted_classesObject



31
32
33
# File 'lib/eac_ruby_utils/yaml.rb', line 31

def permitted_classes
  DEFAULT_PERMITTED_CLASSES
end

.sanitize(object) ⇒ Object



35
36
37
# File 'lib/eac_ruby_utils/yaml.rb', line 35

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

.yaml?(object) ⇒ Boolean

Returns:



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

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

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