Class: Generator

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

Instance Method Summary collapse

Constructor Details

#initialize(document_content, input_name, output_directory) ⇒ Generator

Returns a new instance of Generator.



28
29
30
31
# File 'lib/generate.rb', line 28

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

Instance Method Details

#context_bindingObject



33
34
35
# File 'lib/generate.rb', line 33

def context_binding
  binding
end

#generate(t) ⇒ Object



47
48
49
50
51
# File 'lib/generate.rb', line 47

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

#load(generator_names) ⇒ Object



37
38
39
40
41
42
43
44
45
# File 'lib/generate.rb', line 37

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

#output_name(t, index) ⇒ Object



53
54
55
56
57
# File 'lib/generate.rb', line 53

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

#runObject



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/generate.rb', line 69

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
    next if Gen.t.discard # Check first to ignore result if no output.
    return out if out.is_a?(Integer)
    next if out.empty? # Allows no output but return value still checked.
    name = output_name(Gen.t, Gen.task_index - 1)
    begin
      save(name, out, Gen.t.executable)
    rescue StandardError => e
      return aargh("Error writing output file: #{name}\n#{e}", 3)
    end
  end
  0
end

#save(name, contents, executable) ⇒ Object



59
60
61
62
63
64
65
66
67
# File 'lib/generate.rb', line 59

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