Class: ValueMapFromFile

Inherits:
Hash
  • Object
show all
Defined in:
lib/datashift/mapping_file_definitions.rb

Overview

This class provides a value map (hash) from a text mapping file

The map file is a text file of delimeted key -> values pairs

SUPPORTED FILE FORMATS:

2 column e.g. a,b
 creates a simple hash {a => b)

3 column e.g. a,b,c
 a,b becomes the key, c is the vaule
 creates a hash { [a,b] => c }

4 column e.g. a,b,c,d
 a,b  becomes the key, c,d the value
 creates a hash { [a,b] => [c,d] }

TODO allow mapping file to be an xml file

Instance Method Summary collapse

Instance Method Details

#intialize(file_path, delim = ',') ⇒ Object



22
23
24
25
26
# File 'lib/datashift/mapping_file_definitions.rb', line 22

def intialize(file_path, delim = ',')
  @delegate_to = {}
  @delim = delim
  load_map(file_path)
end

#load_map(file_path = nil, delim = ',') ⇒ Object

Raises:

  • (ArgumentError)


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

def load_map(file_path = nil, delim = ',')
  @file = file_path unless file_path.nil?
  @delim = delim

  raise ArgumentError.new("Can not read map file: #{@file}") unless File.readable?(@file)

  File.open(@file).each_line do |line|
    next unless(line && line.chomp!)

    values = line.split(@delim)

    case values.nitems
      when 2 then self.store(values[0], values[1])
      when 3 then self.store([values[0], values[1]], values[2])
      when 4 then self.store([values[0], values[1]],[values[2], values[3]])
    else
      raise ArgumentError.new("Bad key,value row in #{@file}: #{values.nitems} number of columns not supported")
    end
  end

  return self
end