Module: IMW::Formats::Json

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

Overview

Defines methods for reading and writing JSON 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/json.rb', line 43

def dump data, options={}
  require 'json'
  write(data.to_json)
  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 JSON data structure is an array, then yield each element

  • if the outermost JSON 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/json.rb', line 21

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