Module: Caligrafo::Reader

Included in:
Caligrafo
Defined in:
lib/caligrafo/reader.rb

Defined Under Namespace

Modules: LineExtension

Instance Method Summary collapse

Instance Method Details

#ler_arquivo(nome, opcoes = {}, &bloco) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/caligrafo/reader.rb', line 3

def ler_arquivo(nome, opcoes={}, &bloco)
  estrutura = (self.is_a?(Class) ? self.estrutura : self.class.estrutura)
  raise 'A estrutura nao foi definida' unless estrutura

  if output = opcoes.delete(:arquivo_retorno)
    output_file = File.new(output, 'w')
    secoes_retorno = opcoes.delete(:secoes_retorno)
    secoes_retorno ||= estrutura.secoes.collect {|secao| secao.nome }
    linha_retorno = 1
  end

  File.open(nome, 'r') do |file|
    while linha = file.gets
      linha.extend LineExtension
      linha.arquivo = estrutura
      linha.descobrir_secao
      linha.numero = file.lineno
      linha.numero_retorno = linha_retorno

      bloco.call linha
      
      if output and secoes_retorno.include? linha.secao
        output_file.puts linha.chomp
        linha_retorno += 1
      end
    end
  end
  
  output_file.close if output
end