Module: OpenAPISourceTools::Common

Defined in:
lib/openapi/sourcetools/common.rb

Overview

Common methods used in programs and elsewhere gathered into one place.

Defined Under Namespace

Modules: Out

Class Method Summary collapse

Class Method Details

.aargh(message, return_value = nil) ⇒ Object



12
13
14
15
16
# File 'lib/openapi/sourcetools/common.rb', line 12

def self.aargh(message, return_value = nil)
  message = message.map(&:to_s).join("\n") if message.is_a? Array
  $stderr.puts message
  return_value
end

.bury(doc, path, value) ⇒ Object



22
23
24
25
26
27
28
29
# File 'lib/openapi/sourcetools/common.rb', line 22

def self.bury(doc, path, value)
  (path.size - 1).times do |k|
    p = path[k]
    doc[p] = {} unless doc.key?(p)
    doc = doc[p]
  end
  doc[path.last] = value
end

.dump_result(output, doc, error_return) ⇒ Object



67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/openapi/sourcetools/common.rb', line 67

def self.dump_result(output, doc, error_return)
  doc = YAML.dump(doc, line_width: 1_000_000) unless doc.is_a?(String)
  if output.nil?
    $stdout.puts doc
  else
    fp = Pathname.new output
    fp.open('w') do |f|
      f.puts doc
    end
  end
  0
rescue StandardError => e
  aargh([ e, "Failed to write output: #{output || 'stdout'}" ], error_return)
end

.load_source(input) ⇒ Object



59
60
61
62
63
64
65
# File 'lib/openapi/sourcetools/common.rb', line 59

def self.load_source(input)
  YAML.safe_load(input.nil? ? $stdin : File.read(input))
rescue Errno::ENOENT
  aargh "Could not load #{input || 'stdin'}"
rescue StandardError => e
  aargh "#{e}\nFailed to read #{input || 'stdin'}"
end

.split_path(p, spec = false) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/openapi/sourcetools/common.rb', line 44

def self.split_path(p, spec = false)
  parts = []
  p = p.strip
  unless spec
    q = p.index('?')
    p.slice!(0...q) unless q.nil?
  end
  p.split('/').each do |s|
    next if s.empty?
    s = { (spec && s.include?('{') ? 'parameter' : 'fixed') => s }
    parts.push(s)
  end
  parts
end

.yesno(boolean) ⇒ Object



18
19
20
# File 'lib/openapi/sourcetools/common.rb', line 18

def self.yesno(boolean)
  boolean ? 'yes' : 'no'
end