Module: ThreeScaleToolbox::ResourceReader

Instance Method Summary collapse

Instance Method Details

#load_resource(resource) ⇒ Object

Load resource from different types of sources. Supported types are: file, URL, stdin Loaded content is returned



7
8
9
10
11
12
# File 'lib/3scale_toolbox/resource_reader.rb', line 7

def load_resource(resource)
  # Json format is parsed as well
  YAML.safe_load(read_content(resource))
rescue Psych::SyntaxError => e
  raise ThreeScaleToolbox::Error, "JSON/YAML validation failed: #{e.message}"
end

#read_content(resource) ⇒ Object

Reads resources from different types of sources. Supported types are: file, URL, stdin Resource raw content is returned



18
19
20
21
22
23
24
25
26
27
# File 'lib/3scale_toolbox/resource_reader.rb', line 18

def read_content(resource)
  case resource
  when '-'
    method(:read_stdin)
  when /\A#{URI::DEFAULT_PARSER.make_regexp}\z/
    method(:read_url)
  else
    method(:read_file)
  end.call(resource)
end

#read_file(filename) ⇒ Object

Detect format from file extension



30
31
32
33
34
35
# File 'lib/3scale_toolbox/resource_reader.rb', line 30

def read_file(filename)
  raise ThreeScaleToolbox::Error, "File not found: #{filename} " unless File.file?(filename)
  raise ThreeScaleToolbox::Error, "File not readable: #{filename} " unless File.readable?(filename)

  File.read(filename)
end

#read_stdin(_resource) ⇒ Object



37
38
39
# File 'lib/3scale_toolbox/resource_reader.rb', line 37

def read_stdin(_resource)
  STDIN.read
end

#read_url(resource) ⇒ Object



41
42
43
# File 'lib/3scale_toolbox/resource_reader.rb', line 41

def read_url(resource)
  Net::HTTP.get(URI.parse(resource))
end