Module: NestedText

Defined in:
lib/nestedtext/encode.rb,
lib/nestedtext.rb,
lib/nestedtext/decode.rb,
lib/nestedtext/dumper.rb,
lib/nestedtext/errors.rb,
lib/nestedtext/parser.rb,
lib/nestedtext/version.rb,
lib/nestedtext/scanners.rb,
lib/nestedtext/constants.rb,
lib/nestedtext/encode_helpers.rb

Overview

Model after JSON NestedText.dump(obj, io=nil) => dumps to string, or to IO if given NestedText.dump_file(obj, filename)

Defined Under Namespace

Modules: NTEncodeMixin Classes: Error

Constant Summary collapse

VERSION =
"1.1.1"

Class Method Summary collapse

Class Method Details

.dump(obj, io: nil, indentation: 4, strict: true) ⇒ Object

TODO: strict should maybe be false by default, as this is what ntpy does. If so, make the same for the load functions.

Raises:



13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/nestedtext/encode.rb', line 13

def self.dump(obj, io: nil, indentation: 4, strict: true)
  # io - additionaly write the out result to IO and still return result.

  raise Errors::DumpBadIO, io unless io.nil? || io.respond_to?(:write) && io.respond_to?(:fsync)

  opts = EncodeOptions.new(indentation, strict)
  dumper = Dumper.new(opts)
  result = dumper.dump obj
  unless io.nil?
    io.write(result)
    io.fsync
  end
  result
end

.dump_file(obj, filename, **kwargs) ⇒ Object



28
29
30
31
32
33
34
# File 'lib/nestedtext/encode.rb', line 28

def self.dump_file(obj, filename, **kwargs)
  raise Errors::DumpFileBadPath, filename unless filename.is_a? String

  File.open(filename, mode = "wt") do |file|
    dump(obj, io: file, **kwargs)
  end
end

.load(ntstring, top_class: Object, strict: true) ⇒ Object



10
11
12
13
14
15
16
17
18
# File 'lib/nestedtext/decode.rb', line 10

def self.load(ntstring, top_class: Object, strict: true)
  # logger = Logger.new(STDOUT) # TODO: make this available to other classes in module. How avoid singleton?
  # logger.info "input=#{raw_input_string}"
  # logger.info "top=#{top}"

  raise Errors::WrongInputTypeError.new([String], ntstring) unless ntstring.nil? || ntstring.is_a?(String)

  Parser.new(StringIO.new(ntstring), top_class, strict: strict).parse
end

.load_file(filename, top_class: Object, strict: true) ⇒ Object



20
21
22
23
24
25
26
27
# File 'lib/nestedtext/decode.rb', line 20

def self.load_file(filename, top_class: Object, strict: true)
  raise Errors::WrongInputTypeError.new([String], filename) unless !filename.nil? && filename.is_a?(String)

  # Open explicitly in text mode to detect \r as line ending.
  File.open(filename, mode = "rt") do |file|
    Parser.new(file, top_class, strict: strict).parse
  end
end