Class: Laser::Cutter::CLI::ConfigFile

Inherits:
Object
  • Object
show all
Defined in:
lib/laser/cutter/cli/config_file.rb

Overview

A configuration saved as JSON. The path '-' stands for STDIN when reading, and for the command's own output when writing.

Constant Summary collapse

STDIO =

The path that stands for STDIN or the command's output.

'-'

Instance Method Summary collapse

Constructor Details

#initialize(path) ⇒ ConfigFile

Returns a new instance of ConfigFile.

Parameters:

  • path (String)


13
14
15
# File 'lib/laser/cutter/cli/config_file.rb', line 13

def initialize(path)
  @path = path
end

Instance Method Details

#read ⇒ Hash{String => Object}

Returns:

  • (Hash{String => Object})

Raises:

  • (Error) —

    when the file is missing, or is not JSON



19
20
21
22
23
# File 'lib/laser/cutter/cli/config_file.rb', line 19

def read
  JSON.parse(@path == STDIO ? $stdin.read : File.read(@path))
rescue SystemCallError, JSON::ParserError => e
  raise Error, "cannot read the configuration from #{@path}: #{e.message}"
end

#write(settings, out) ⇒ void

This method returns an undefined value.

Parameters:

  • settings (Hash)
  • out (IO) —

    where '-' writes to

Raises:

  • (Error) —

    when the file cannot be written



29
30
31
32
33
34
# File 'lib/laser/cutter/cli/config_file.rb', line 29

def write(settings, out)
  json = JSON.pretty_generate(settings)
  @path == STDIO ? out.puts(json) : File.write(@path, "#{json}\n")
rescue SystemCallError => e
  raise Error, "cannot write the configuration to #{@path}: #{e.message}"
end