Class: LanGrove::Ext::RecursiveString

Inherits:
Object
  • Object
show all
Defined in:
lib/langrove/ext/recursive_string.rb

Class Method Summary collapse

Class Method Details

.decode(data, config = nil) ⇒ Object



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
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/langrove/ext/recursive_string.rb', line 7

def self.decode( data, config = nil )

  config = {} if config.nil?
  config[:delim_1] = ',' if config[:delim_1].nil?
  config[:delim_2] = ':' if config[:delim_2].nil?
  
  #
  # <config> = {
  #   :delim_1 => ','
  #   :delim_2 => ':'
  #   :pre_sub => { #optional
  #     :thingone => <regex to match thing>,
  #     :another => <regex>
  #   }
  # }
  # 
  # <data> = " col1:value1, col2 :value2, col2: value3 "
  
  #
  # out-substitute the fields known to 
  # contain a delimiter 
  #  
  copy_data = data
  pre_subs = {}
  delims = []
  
  unless config[:pre_sub].nil?
    config[:pre_sub].each do |key, value|
      
      begin
        matches = /#{value}/.match( data )
        matches[1..-1].each do |match|
          
        
          copy_data.gsub!( match, "__sub__#{pre_subs.length}__" )
          pre_subs["__sub__#{pre_subs.length}__"] = match
          
          
        end if matches and matches.length > 1
      end unless value.nil?
      
    end if config[:pre_sub].is_a?( Hash ) 
  end
  
  config.each do |key, value| 
    
    delims << value if /delim_/.match( key )
    
  end
  
  result = {}
  copy_data.split( delims.shift ).each do |pair|
    
    key,value = pair.split( delims[0] )
    key.gsub!(/^\s/,'')
    key.gsub!(/\s$/,'')
    value.gsub!(/^\s/,'') unless value.nil?
    value.gsub!(/\s$/,'') unless value.nil?
    
    #
    # in-substitute the fields known to 
    # contain a delimiter 
    #
    value = pre_subs[value] if pre_subs.has_key?(value)  
    
    key.downcase! if config[:downcase_key]

    key = key.to_sym unless config[:sym_key] == false

    result[ key ] = value
    
  end
  
  return result
  
end