Class: MARC::Writer
- Inherits:
-
Object
- Object
- MARC::Writer
- Defined in:
- lib/marc/writer.rb
Overview
A class for writing MARC records as MARC21.
Class Method Summary collapse
-
.encode(record) ⇒ Object
a static method that accepts a MARC::Record object and returns the record encoded as MARC21 in transmission format.
Instance Method Summary collapse
-
#close ⇒ Object
close underlying filehandle.
-
#initialize(file) ⇒ Writer
constructor
the constructor which you must pass a file path or an object that responds to a write message.
-
#write(record) ⇒ Object
write a record to the file or handle.
Constructor Details
#initialize(file) ⇒ Writer
the constructor which you must pass a file path or an object that responds to a write message
10 11 12 13 14 15 16 17 18 |
# File 'lib/marc/writer.rb', line 10 def initialize(file) if file.class == String @fh = File.new(file,"w") elsif file.respond_to?('write') @fh = file else throw "must pass in file name or handle" end end |
Class Method Details
.encode(record) ⇒ Object
a static method that accepts a MARC::Record object and returns the record encoded as MARC21 in transmission format
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
# File 'lib/marc/writer.rb', line 38 def self.encode(record) directory = '' fields = '' offset = 0 for field in record.fields # encode the field field_data = '' if field.class == MARC::DataField warn("Warn: Missing indicator") unless field.indicator1 && field.indicator2 field_data = (field.indicator1 || " ") + (field.indicator2 || " ") for s in field.subfields field_data += SUBFIELD_INDICATOR + s.code + s.value end elsif field.class == MARC::ControlField field_data = field.value end field_data += END_OF_FIELD # calculate directory entry for the field field_length = field_data.length() directory += sprintf("%03s%04i%05i", field.tag, field_length, offset) # add field to data for other fields fields += field_data # update offset for next field offset += field_length end # determine the base (leader + directory) base = record.leader + directory + END_OF_FIELD # determine complete record marc = base + fields + END_OF_RECORD # update leader with the byte offest to the end of the directory marc[12..16] = sprintf("%05i", base.length()) # update the record length marc[0..4] = sprintf("%05i", marc.length()) # store updated leader in the record that was passed in record.leader = marc[0..LEADER_LENGTH-1] # return encoded marc return marc end |
Instance Method Details
#close ⇒ Object
close underlying filehandle
30 31 32 |
# File 'lib/marc/writer.rb', line 30 def close @fh.close end |