Class: WavefrontCli::Helper::LoadFile

Inherits:
Object
  • Object
show all
Defined in:
lib/wavefront-cli/helpers/load_file.rb

Overview

Give it a path to a file (as a string) and it will return the contents of that file as a Ruby object. Automatically detects JSON and YAML. Raises an exception if it doesn’t look like either. If path is ‘-’ then it will read STDIN.

Returns:

  • (Hash)

    a Ruby object of the loaded file

Raises:

  • WavefrontCli::Exception::UnsupportedFileFormat if the filetype is unknown.

  • pass through any error loading or parsing the file

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path) ⇒ LoadFile

Returns a new instance of LoadFile.



22
23
24
# File 'lib/wavefront-cli/helpers/load_file.rb', line 22

def initialize(path)
  @path = path
end

Instance Attribute Details

#pathObject (readonly)

Returns the value of attribute path.



20
21
22
# File 'lib/wavefront-cli/helpers/load_file.rb', line 20

def path
  @path
end

Instance Method Details

#loadObject



26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/wavefront-cli/helpers/load_file.rb', line 26

def load
  return load_from_stdin if path == '-'

  file = Pathname.new(path)
  extname = file.extname.downcase

  raise WavefrontCli::Exception::FileNotFound unless file.exist?

  return load_json(file) if extname == '.json'
  return load_yaml(file) if %w[.yaml .yml].include?(extname)

  raise WavefrontCli::Exception::UnsupportedFileFormat
end