Skip to content

Instantly share code, notes, and snippets.

@apeiros
Created November 10, 2008 03:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save apeiros/23413 to your computer and use it in GitHub Desktop.
Save apeiros/23413 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
# hackery to simulate a file
require 'stringio'
RealFile = File
Object.send(:remove_const, :File)
File = StringIO
def StringIO.open(data); x=new(data);x.rewind; x; end
# end of hackery
data = <<EODATA
SEQ_NAME: test1
SEQ: ATCG
---
SEQ_NAME: test2
SEQ: ATCGA---
---
SEQ_NAME: test3
SEQ: ATCGAT
---
SEQ_NAME: test4
SEQ: --------
---
EODATA
class BioPieces
RECORD_DELIMITER = "\n---\n"
class Record
attr_reader :__hash__
def initialize(data)
@__hash__ = data
end
def method_missing(name, *a, &b)
if a.empty? && @__hash__.has_key?(name) then
@__hash__[name]
else
super # get the original exception
end
end
def to_s
@__hash__.map { |key, value|
"#{key}: #{value}"
}.join("\n")+RECORD_DELIMITER
end
def to_hash
@__hash__.dup
end
end
def self.file(path)
bp = new(File.open(path))
yield bp if block_given?
bp
ensure
# if no block was given, the user wants the BioPieces instance
# with a still open File so he can read it, so only close if a block
# had been given.
bp.close if block_given?
end
def initialize( file )
@stream = file
end
def close
@stream.close if @stream.respond_to? :close
end
def record_get
return unless block = @stream.gets(RECORD_DELIMITER)
block.chomp!(RECORD_DELIMITER)
data = Hash[*block.scan(/(\w+):\s+(.*)/).flatten]
Record.new(data)
end
def each
yield record_get until @stream.eof?
self # not to have a messy return value
end
end
#path = "test.stream"
path = data # using the hack
BioPieces.file(path) do |bp|
bp.each { |record|
puts record
}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment