Class: OpenAPISourceTools::Generator

Inherits:
Object
  • Object
show all
Defined in:
lib/openapi/sourcetools/generate.rb

Overview

Runs all tasks that generate the results. Used internally by openapi-generate.

Instance Method Summary collapse

Constructor Details

#initialize(document_content, input_name, output_directory, config_prefix) ⇒ Generator

Returns a new instance of Generator.



31
32
33
34
# File 'lib/openapi/sourcetools/generate.rb', line 31

def initialize(document_content, input_name, output_directory, config_prefix)
  Gen.setup(document_content, input_name, output_directory, config_prefix)
  Gen.loaders = Loaders.loaders
end

Instance Method Details

#context_bindingObject



36
37
38
# File 'lib/openapi/sourcetools/generate.rb', line 36

def context_binding
  binding
end

#generate(t) ⇒ Object



50
51
52
53
54
# File 'lib/openapi/sourcetools/generate.rb', line 50

def generate(t)
  t.generate(context_binding)
rescue Exception => e
  Common.aargh(e.to_s, 4)
end

#load(generator_names) ⇒ Object



40
41
42
43
44
45
46
47
48
# File 'lib/openapi/sourcetools/generate.rb', line 40

def load(generator_names)
  generator_names.each do |name|
    idx = Gen.loaders.index { |loader| loader.call(name) }
    return Common.aargh("No loader could handle #{name}", 2) if idx.nil?
  end
  0
rescue StandardError => e
  Common.aargh(e.to_s, 2)
end

#output_name(t, index) ⇒ Object



56
57
58
59
60
# File 'lib/openapi/sourcetools/generate.rb', line 56

def output_name(t, index)
  name = t.output_name
  name = "#{index}.txt" if name.nil?
  File.join(Gen.outdir, name)
end

#runObject



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/openapi/sourcetools/generate.rb', line 74

def run
  # This allows tasks to be added while processing.
  # Not intended to be done but might prove handy.
  # Also exposes current task index in case new task is added in the middle.
  Gen.task_index = 0
  while Gen.task_index < Gen.tasks.size
    Gen.t = Gen.tasks[Gen.task_index]
    out = generate(Gen.t)
    Gen.task_index += 1
    return out if out.is_a?(Integer)
    next if Gen.t.discard || out.empty?
    name = output_name(Gen.t, Gen.task_index - 1)
    begin
      save(name, out, Gen.t.executable)
    rescue StandardError => e
      return Common.aargh("Error writing output file: #{name}\n#{e}", 3)
    end
  end
  0
end

#save(name, contents, executable) ⇒ Object



62
63
64
65
66
67
68
69
70
71
72
# File 'lib/openapi/sourcetools/generate.rb', line 62

def save(name, contents, executable)
  d = File.dirname(name)
  FileUtils.mkdir_p(d) unless File.directory?(d)
  f = File.new(name, File::WRONLY | File::CREAT | File::TRUNC)
  s = executable ? f.stat : nil
  f.write(contents)
  f.close
  return unless executable
  mode = OpenAPISourceTools.executable_bits_on(s.mode)
  File.chmod(mode, name) unless mode == s.mode
end