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



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/external_migration/text_fixed.rb', line 27

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+/ }
    puts row.to_yaml
    @migration.migreate_row! row
  end
  file.close
  
end

#schema=(schema) ⇒ Object



23
24
25
# File 'lib/external_migration/text_fixed.rb', line 23

def schema=(schema)
  @schema = schema
end