]> git.donarmstrong.com Git - biopieces.git/blob - code_ruby/Maasha/biopieces.rb
fixes and stuff
[biopieces.git] / code_ruby / Maasha / biopieces.rb
1 class BioPieces
2         RECORD_DELIMITER = "\n---\n"
3
4         class Record
5                 attr_reader :__hash__
6  
7                 def initialize( data )
8                         @__hash__ = data
9                 end
10         
11                 def method_missing( name, *args, &block )
12                         if args.empty? && @__hash__.has_key?( name ) then
13                                 @__hash__[ name ]
14                         else
15                                 super # get the original exception
16                         end
17                 end
18         
19                 def to_s
20                         @__hash__.map { | key, value | "#{ key }: #{ value }" }.join( "\n" ) + RECORD_DELIMITER
21                 end
22         
23                 def to_hash
24                         @__hash__.dup
25                 end
26         end
27  
28         def self.file( path )
29                 bp = new( File.open( path ) )
30                 yield bp if block_given?
31                 bp
32         ensure
33                 # if no block was given, the user wants the BioPieces instance
34                 # with a still open File so he can read it, so only close if a block
35                 # had been given.
36                 bp.close if block_given?
37         end
38  
39         def initialize( stream )
40                 @stream = stream
41         end
42  
43         def close
44                 @stream.close if @stream.respond_to? :close
45         end
46  
47         def record_get
48                 return unless block = @stream.gets( RECORD_DELIMITER )
49  
50                 block.chomp!( RECORD_DELIMITER )
51                 data = Hash[ *block.split( /: |\n/, 2 ) ]
52                 Record.new( data )
53         end
54   
55         def each
56                 yield record_get until @stream.eof?
57                 self # not to have a messy return value
58         end
59 end
60
61
62 __END__