class MiGA::Json

Taxonomic classifications in MiGA.

Public Class Methods

default_opts(opts = {}) click to toggle source

Default parsing options. Supported opts keys:

  • :contents: If true, the input is assumed to be the contents to parse, not the path to a JSON file.

  • :default: A base to attach the parsed hash. A Hash or a String (path).

  • :additions: If addition classes should be parsed. By default is false.

  • :symbolize: If names should be symbolized. By default it's true if additions is false, or false otherwise. They can both be false, but an exception will be raised if both are true

# File lib/miga/json.rb, line 19
def default_opts(opts = {})
  opts[:contents] ||= false
  opts[:additions] ||= false
  opts[:symbolize] = !opts[:additions] if opts[:symbolize].nil?
  if opts[:additions] and opts[:symbolize]
    raise 'JSON additions are not supported with symbolized names'

generate(obj, path = nil) click to toggle source

Generates and returns prettyfied JSON to represent obj. If path is passed, it saves the JSON in that file.

# File lib/miga/json.rb, line 54
def generate(obj, path = nil)
  y = JSON.pretty_generate(obj), 'w') { |fh| fh.print y } unless path.nil?
parse(path, opts = {}) click to toggle source

Parse a JSON file in path and return a hash. Optionally, use default as the base to attach the parsed hash. default can be a Hash or a String (path). See default_opts for supported opts.

# File lib/miga/json.rb, line 35
def parse(path, opts = {})
  opts = default_opts(opts)
  cont = opts[:contents] ? path :
  raise "Empty descriptor: #{opts[:contents] ? "''" : path}." if cont.empty?

  y = JSON.parse(cont,
                 symbolize_names: opts[:symbolize],
                 create_additions: opts[:additions])
  unless opts[:default].nil?
    opts[:default] = parse(opts[:default]) if opts[:default].is_a? String
    y.each { |k, v| opts[:default][k] = v }
    y = opts[:default]