Module: IMW::Formats::Yaml

Defined in:
lib/imw/formats/yaml.rb

Overview

Provides methods for reading and writing YAML data.

Instance Method Summary collapse

Instance Method Details

#dump(data, options = {}) ⇒ Object

Dump the data into this resource. It must be opened for writing.

Parameters:

  • data (Hash, String, Array, Fixnum)

    the Ruby object to dump

  • options (Hash) (defaults to: {})

    a customizable set of options

Options Hash (options):

  • :persist (true, false) — default: false

    Don’t close the IO object after writing



43
44
45
46
47
48
# File 'lib/imw/formats/yaml.rb', line 43

def dump data, options={}
  require 'yaml'
  write(data.to_yaml)
  io.close unless options[:persist]
  self
end

#load(&block) ⇒ Hash, ...

Return the content of this resource.

Will try to be smart about iterating over the data when passed a block.

  • if the outermost YAML data structure is an array, then yield each element

  • if the outermost YAML data structure is a mapping, then yield each key, value pair

  • otherwise just yield the structure

Returns:



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/imw/formats/yaml.rb', line 21

def load &block
  require 'yaml'
  yaml = YAML.load(read)
  if block_given?
    case yaml
    when Array
      yaml.each      { |obj| yield obj }
    when Hash
      yaml.each_pair { |key, value| yield key, value }
    else
      yield yaml
    end
  else
    yaml
  end
end