Class: ONIX::Writer

Inherits:
Object
  • Object
show all
Defined in:
lib/onix/writer.rb

Overview

The primary way to write a new ONIX file.

Heres a quick example. The generated file will be nice and boring, as the header and product objects have no data in them, but you get the idea.

File.open("output.xml","w") do |output|
  header = ONIX::Header.new
  ONIX::Writer.open(output, header) do |writer|
    writer << ONIX::Product.new
    writer << ONIX::Product.new
  end
end

If you prefer, you can build your products using the APAProduct shim layer.

File.open("output.xml","w") do |output|
  header = ONIX::Header.new
  ONIX::Writer.open(output, header) do |writer|
    writer << ONIX::APAProduct.new
    writer << ONIX::APAProduct.new
  end
end

Constant Summary collapse

DOCTYPE =
"http://www.editeur.org/onix/2.1/03/reference/onix-international.dtd"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(output, header) ⇒ Writer

Default constructor.

Raises:

  • (ArgumentError)


32
33
34
35
36
37
38
39
# File 'lib/onix/writer.rb', line 32

def initialize(output, header)
  raise ArgumentError, 'msg must be an ONIX::Header object' unless header.kind_of?(ONIX::Header)
  @output = output
  @header = header
  @finished = false

  start_document
end

Class Method Details

.open(output, header) ⇒ Object



65
66
67
68
69
70
71
72
73
# File 'lib/onix/writer.rb', line 65

def self.open(output, header)
  if block_given?
    writer = self.new(output, header)
    yield writer
    writer.end_document
  else
    self.new(output, header)
  end
end

Instance Method Details

#<<(product) ⇒ Object



46
47
48
49
50
51
52
53
54
# File 'lib/onix/writer.rb', line 46

def << (product)
  unless product.kind_of?(ONIX::Product) || product.kind_of?(ONIX::SimpleProduct)
    raise ArgumentError, 'product must be an ONIX::Product or ONIX::SimpleProduct'
  end
  raise "Can't add products to a finished writer" if finished?

  @output.write(product.to_xml.to_s)
  @output.write("\n")
end

#end_documentObject



56
57
58
59
# File 'lib/onix/writer.rb', line 56

def end_document
  @output.write("</ONIXMessage>\n")
  @finished = true
end

#finished?Boolean

Returns:

  • (Boolean)


61
62
63
# File 'lib/onix/writer.rb', line 61

def finished?
  @finished
end