Class: ExternalMigration::TextFixed

Inherits:
Object
  • Object
show all
Includes:
Decoder
Defined in:
lib/external_migration/text_fixed.rb

Overview

Schema format:

format: TXT_FIXED url: text to read ignore_lines: default 1 encoding: default ‘windows-1251:utf-8’

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(schema) ⇒ TextFixed

Returns a new instance of TextFixed.



17
18
19
20
21
# File 'lib/external_migration/text_fixed.rb', line 17

def initialize(schema)
  self.schema = schema
  @ignore_lines = schema[:ignore_lines] || 1
  @enconding = schema[:encoding] || 'windows-1251:utf-8'
end

Instance Attribute Details

#ignore_linesObject

Returns the value of attribute ignore_lines.



15
16
17
# File 'lib/external_migration/text_fixed.rb', line 15

def ignore_lines
  @ignore_lines
end

#migrationObject

Returns the value of attribute migration.



15
16
17
# File 'lib/external_migration/text_fixed.rb', line 15

def migration
  @migration
end

Instance Method Details

#migrate!Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/external_migration/text_fixed.rb', line 37

def migrate!
  puts "opening file #{@schema[:url]}"
  file = File.open(Rails.root.join(@schema[:url]), "r:#{@enconding}")
  file.each_line do |line|
    if @ignore_lines>0
      @ignore_lines -= 1
      next line
    end
    
    row = {}
    line_index = 0
    @schema[:columns].each do |column, column_prop|
      row[column.to_sym] = line[line_index..(line_index+column_prop[:length]-1)]
      row[column.to_sym].strip! if @schema[:strip_columns] == :true && !row[column.to_sym].nil?
      line_index += column_prop[:length]
    end
    row.keys.each {|k| row.delete k if k.to_s =~ /ignore\d+/ }
    @migration.migrate_row! row

    next_schema_line
  end
  file.close
  
end

#next_schema_lineObject



62
63
64
65
66
67
68
# File 'lib/external_migration/text_fixed.rb', line 62

def next_schema_line
  if @schema_multiple_lines
    @schema_line_index += 1
    @schema_line_index = 0 if @schema_line_index >= @schema_lines.size
    @schema[:columns] = @schema[:lines][@schema_lines[@schema_line_index]]
  end
end

#schema=(schema) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/external_migration/text_fixed.rb', line 23

def schema=(schema)
  
  if schema[:multiple_lines] == :true
    @schema_multiple_lines = true
    @schema_line_index = -1
    @schema = schema
    @schema_lines  = @schema.columns.keys
    @schema[:lines] = @schema[:columns] #backup layout
    next_schema_line
  else
    @schema  = schema
  end
end