Class: Bddgenx::PDFExporter

Inherits:
Object
  • Object
show all
Defined in:
lib/bddgenx/reports/pdf_exporter.rb

Overview

Gera documentos PDF baseados em arquivos .feature.

Class Method Summary collapse

Class Method Details

.camel_case(str) ⇒ String

Converte uma string para formato camelCase, removendo caracteres especiais.

Parameters:

  • str (String)

    A string de entrada a ser transformada.

Returns:

  • (String)

    String no formato camelCase.



63
64
65
66
67
# File 'lib/bddgenx/reports/pdf_exporter.rb', line 63

def self.camel_case(str)
  clean = str.gsub(/[^0-9A-Za-z ]/, '')
  parts = clean.split(/ |_/)
  ([parts.first&.downcase] + (parts[1..] || []).map(&:capitalize)).join
end

.exportar_arquivo(origem, destino) ⇒ void

This method returns an undefined value.

Gera um documento PDF a partir de um arquivo .feature, aplicando estilos de cabeçalhos, cenários, passos e tabelas conforme padrões Cucumber.

Parameters:

  • origem (String)

    Caminho para o arquivo .feature de origem.

  • destino (String)

    Caminho onde o PDF será salvo.



75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/bddgenx/reports/pdf_exporter.rb', line 75

def self.exportar_arquivo(origem, destino)
  FileUtils.mkdir_p(File.dirname(destino))
  conteudo = File.read(origem, encoding: 'utf-8')

  Prawn::Document.generate(destino, page_size: 'A4', margin: 50) do |pdf|
    pdf.font 'Courier'
    pdf.font_size 9

    table_buffer = []

    conteudo.each_line do |linha|
      text = linha.chomp

      # Agrega linhas de tabela até o bloco terminar
      if text =~ /^\s*\|.*\|/i
        # Remove bordas laterais e separa colunas
        row = text.gsub(/^\s*\||\|\s*$/, '').split('|').map(&:strip)
        table_buffer << row
        next
      elsif table_buffer.any?
        # Renderiza tabela acumulada
        pdf.table(table_buffer, header: true, width: pdf.bounds.width) do
          self.header      = true
          self.row_colors  = ['EEEEEE', 'FFFFFF']
          self.cell_style = { size: 8, font: 'Courier' }
        end
        pdf.move_down 4
        table_buffer.clear
      end

      case text
      when /^\s*(Feature|Funcionalidade):/i
        pdf.move_down 6
        pdf.text text, size: 14, style: :bold
        pdf.move_down 4
      when /^\s*(Background):/i
        pdf.text text, size: 11, style: :italic
        pdf.move_down 4
      when /^\s*(Scenario(?: Outline)?|Esquema do Cenário):/i
        pdf.move_down 6
        pdf.text text, size: 12, style: :bold
        pdf.move_down 4
      when /^\s*(Examples|Exemplos):/i
        pdf.text text, size: 11, style: :bold
        pdf.move_down 4
      when /^\s*@/i
        pdf.text text, size: 8, style: :italic
        pdf.move_down 4
      when /^(?:\s*)(Given|When|Then|And|But|Dado|Quando|Então|E|Mas)\b/i
        # Passo Gherkin: destaca palavra-chave e texto
        keyword, rest = text.strip.split(' ', 2)
        pdf.indent(20) do
          pdf.formatted_text [
                               { text: keyword, styles: [:bold] },
                               { text: rest ? " #{rest}" : '' }
                             ], size: 9
        end
        pdf.move_down 2
      when /^\s*$/
        pdf.move_down 4
      else
        pdf.text text
      end
    end

    # Renderiza tabela remanescente, se houver
    if table_buffer.any?
      pdf.table(table_buffer, header: true, width: pdf.bounds.width) do
        self.header      = true
        self.row_colors  = ['EEEEEE', 'FFFFFF']
        self.cell_style = { size: 8, font: 'Courier' }
      end
      pdf.move_down 4
    end

    # Numeração de páginas
    pdf.number_pages 'Página <page> de <total>', align: :right, size: 8
  end
rescue => e
  warn I18n.t('errors.pdf_generation_failed', file: origem, error: e.message)
end

.exportar_todos(caminho_feature: nil, only_new: false) ⇒ Hash<Symbol, Array<String>>

Gera PDFs de features, criando um para cada arquivo .feature ou apenas para o especificado em caminho_feature.

Parameters:

  • caminho_feature (String, nil) (defaults to: nil)

    Caminho para um arquivo .feature específico. Se nil ou vazio, gera para todos os arquivos em features/*.feature.

  • only_new (Boolean) (defaults to: false)

    Se true, não sobrescreve arquivos PDF já existentes.

Returns:

  • (Hash<Symbol, Array<String>>)

    Retorna um hash com duas chaves:

    • :generated => array de caminhos dos PDFs gerados

    • :skipped => array de caminhos dos PDFs que foram pulados



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/bddgenx/reports/pdf_exporter.rb', line 27

def self.exportar_todos(caminho_feature: nil, only_new: false)
  FileUtils.mkdir_p('reports/pdf')
  features_list = if caminho_feature && !caminho_feature.empty?
                    [caminho_feature]
                  else
                    Dir.glob('features/*.feature')
                  end

  generated = []
  skipped   = []

  features_list.each do |feature|
    unless File.file?(feature)
      warn I18n.t('errors.feature_not_found', feature: feature)
      next
    end

    nome     = File.basename(feature, '.feature')
    destino  = "reports/pdf/#{camel_case(nome)}.pdf"

    if only_new && File.exist?(destino)
      skipped << destino
      next
    end

    exportar_arquivo(feature, destino)
    generated << destino
  end

  { generated: generated, skipped: skipped }
end