class BioDSL::Fasta

Class for reading and writing FASTA files.

Attributes

seq[RW]
seq_name[RW]

Public Class Methods

new(io) click to toggle source
# File lib/BioDSL/fasta.rb, line 63
def initialize(io)
  @io        = io
  @seq_name  = nil
  @seq       = ''
  @got_first = nil
  @got_last  = nil
end
open(*args) { |new(ios)| ... } click to toggle source
# File lib/BioDSL/fasta.rb, line 35
def self.open(*args)
  ios = IO.open(*args)

  if block_given?
    begin
      yield new(ios)
    ensure
      ios.close
    end
  else
    return new(ios)
  end
end
read(*args) click to toggle source
# File lib/BioDSL/fasta.rb, line 49
def self.read(*args)
  entries = []

  Fasta.open(*args) do |ios|
    ios.each do |entry|
      entries << entry
    end
  end

  entries
end

Public Instance Methods

each() { |entry| ... } click to toggle source
# File lib/BioDSL/fasta.rb, line 71
def each
  while (entry = next_entry)
    yield entry
  end
end
next_entry() click to toggle source

Method to get the next FASTA entry form an ios and return this as a Seq object. If no entry is found or eof then nil is returned.

# File lib/BioDSL/fasta.rb, line 83
def next_entry
  @io.each do |line|
    line.chomp!

    next if line.empty?

    if line[0] == '>'
      if !@got_first && !@seq.empty?
        unless @seq.empty?
          fail FastaError, 'Bad FASTA format -> content before Fasta ' \
                           "header: #{@seq}"
        end
      end

      @got_first = true

      if @seq_name
        entry     = Seq.new(seq_name: @seq_name, seq: @seq)
        @seq_name = line[1..-1]
        @seq      = ''

        if @seq_name.empty?
          fail FastaError, 'Bad FASTA format -> truncated Fasta header: ' \
                           'no content after \'>\''
        end

        return entry
      else
        @seq_name = line[1..-1]

        if @seq_name.empty?
          fail FastaError, 'Bad FASTA format -> truncated Fasta header: ' \
                           ' no content after \'>\''
        end
      end
    else
      @seq << line
    end
  end

  if @seq_name
    @got_last = true
    entry     = Seq.new(seq_name: @seq_name, seq: @seq)
    @seq_name = nil
    return entry
  end

  if !@got_last && !@seq.empty?
    fail FastaError, 'Bad FASTA format -> content witout Fasta header: ' +
      @seq
  end

  nil
end
puts(*args) click to toggle source
# File lib/BioDSL/fasta.rb, line 77
def puts(*args)
  @io.puts(*args)
end