Class: EDI::Collection

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/edi/edi2json.rb

Instance Method Summary collapse

Instance Method Details

#hash_nameObject



8
9
10
11
12
13
14
15
16
# File 'lib/edi/edi2json.rb', line 8

def hash_name
  # If this is the trigger node for a segment group, use the 
  # group name. Otherwise, use the segment name.
  if self.respond_to?(:is_tnode?) and self.is_tnode?
    self.sg_name
  else
    self.name
  end
end

#to_hashObject



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
# File 'lib/edi/edi2json.rb', line 18

def to_hash
  result = {}
  
  self.each { |child|
    if self[child.name].length > 1 and result[child.name].nil?
      result[child.name] = []
    end
    if child.is_a?(Collection)
      # Data elements first
      hash = child.to_hash
      unless hash.empty?
        if result[child.name].is_a?(Array)
          result[child.name] << hash
        else
          result[child.name] = hash
        end
      end
    else
      unless child.value.nil?
        if result[child.name].is_a?(Array)
          result[child.name] << child.value
        else
          result[child.name] = child.value
        end
      end
    end
    if (result[child.name].is_a?(Array) or result[child.name].is_a?(Hash)) and result[child.name].empty?
      result.delete(child.name)
    end
  }
  
  # If this is the trigger node for a segment group, 
  # make this the first segment in the group.
  if self.respond_to?(:is_tnode?) and self.is_tnode?
    result = [[self.name, result]]
    self.children.each { |segment|
      result << [segment.hash_name, segment.to_hash]
    }
  end
  
  result
end

#to_json(*a) ⇒ Object



61
62
63
# File 'lib/edi/edi2json.rb', line 61

def to_json(*a)
  self.to_hash.to_json(*a)
end