1
1
module ANVL
2
2
class Document # < Hash
3
+ # Parse an ANVL formatted string into an ANVL::Document
4
+ # @param String
3
5
def self . parse str
4
6
anvl = self . new str
5
7
anvl
6
8
end
7
9
10
+ # ANVL key/value pairs
8
11
attr_reader :entries
9
12
10
- def initialize obj = nil
13
+ # @param [String, Hash] obj optional ANVL formatted string or hash values
14
+ def initialize anvl_string_or_hash = nil
11
15
@entries = Array . new
12
16
13
- case obj
17
+ case anvl_string_or_Hash
14
18
when Hash
15
- self . push obj
19
+ self . push anvl_string_or_hash
16
20
17
21
when String
18
- lines = obj . gsub ( /\s ?\n \s +/ , ' ' ) . split ( "\n " )
22
+ lines = anvl_string_or_hash . gsub ( /\s ?\n \s +/ , ' ' ) . split ( "\n " )
19
23
20
24
lines . each_with_index do |str , i |
21
25
case str
@@ -28,20 +32,22 @@ def initialize obj = nil
28
32
end
29
33
end
30
34
31
- end if obj
35
+ end if anvl_string_or_hash
32
36
33
37
add_entries_methods
34
38
35
39
gc!
36
40
end
37
41
42
+ # @return [String] an ANVL-formatted string
38
43
def to_s
39
44
gc!
40
45
@entries . map do |obj |
41
46
obj . to_anvl
42
47
end . join "\n "
43
48
end
44
49
50
+ # @return [Hash] an ordinary hash representation of the ANVL document
45
51
def to_h
46
52
gc!
47
53
h = { }
@@ -58,6 +64,11 @@ def to_h
58
64
h
59
65
end
60
66
67
+ # Retrieve an ANVL entry
68
+ # @param [String] display_label
69
+ # @param [Hash] args
70
+ # @option args [Boolean] :raw
71
+ # @return [Array, String]
61
72
def [] display_label , args = { }
62
73
v = @entries . select { |x | x =~ display_label }
63
74
v &&= v . map { |x | x . to_s } unless args [ :raw ]
@@ -66,6 +77,10 @@ def [] display_label, args = {}
66
77
end
67
78
alias_method :fetch , :[]
68
79
80
+ # Set an ANVL key/value pair
81
+ # @param [String] display_label
82
+ # @param [String] value
83
+ # @param [Boolean] append (if false (the default), it will overwrite any existing tags for the label)
69
84
def []= display_label , value , append = false
70
85
label = convert_label display_label
71
86
value = [ value ] unless value . is_a? Array
@@ -79,9 +94,10 @@ def []= display_label, value, append = false
79
94
end
80
95
end
81
96
end
82
-
83
97
alias_method :store , :[]=
84
98
99
+ # Append an ANVL key/value pair to the document
100
+ # @param [Hash] key => value to append
85
101
def push hash
86
102
hash . each do |label , value |
87
103
self . store label , value , true
0 commit comments