Class: RMARC::MarcStreamReader

Inherits:
Object
  • Object
show all
Defined in:
lib/rmarc/marc_stream_reader.rb

Overview

This class provides an iterator over a collection of MARC records in ISO 2709 format.

Example usage:

reader = RMARC::MarcStreamReader.new("file.mrc")
while reader.has_next
    record = reader.next()
end

You can also pass a file object:

input = File.new("file.mrc")
reader = RMARC::MarcStreamReader.new(input)
while reader.has_next
    record = reader.next()
end
input.close

Or any other IO subclass.

Instance Method Summary collapse

Constructor Details

#initialize(input) ⇒ MarcStreamReader

Default constructor



137
138
139
140
141
142
143
144
145
# File 'lib/rmarc/marc_stream_reader.rb', line 137

def initialize(input)
  if input.class == String
    @input = File.new(input)
  elsif input.class == File
    @input = input
  else
    throw "Unable to read from path or file"                
  end
end

Instance Method Details

#has_nextObject

Returns true if the iteration has more records, false otherwise.



128
129
130
131
132
133
134
# File 'lib/rmarc/marc_stream_reader.rb', line 128

def has_next
  if @input.eof == false
    return true
  else 
    return false
  end
end

#nextObject

Returns the next record in the iteration.



87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
# File 'lib/rmarc/marc_stream_reader.rb', line 87

def next
  ldr = @input.read(24)
  
  raise "Unexpected EOF while reading record label" if ldr == nil
  
  leader = Leader.new(ldr)
  
  record = Record.new(leader)
  
  length = leader.base_address - 25
  
  raise "Invalid directory" if length % 12 != 0
  
  dir = @input.read(length)
  
  entries = length / 12
  
  raise "Expected field terminator" if @input.read(1) != Constants.FT
  
  start = 0
  
  entries.times do
    entry = Directory.new(dir[start, 3], dir[start += 3, 4], dir[start += 4, 5])
    if (entry.tag.to_i < 10)
      data = @input.read(entry.length)
      
      raise "Unexpected EOF while reading field with tag #{entry.tag}" if data == nil
      
      record.add(ControlField.new(entry.tag, data.chop))
    else
      record.add(parse_data_field(entry))
    end
    start += 5
  end
  
  raise "Expected record terminator" if @input.read(1) != Constants.RT
  
  return record
end