Class: Xliff::Header

Inherits:
Object
  • Object
show all
Defined in:
lib/xliff/header.rb

Overview

Models a file header.

Headers have an element and a set of key/value pairs encoded as XML attributes.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(element: nil, attributes: {}) ⇒ Header

Create a blank Header object

Most often used to build an XLIFF file by hand.

Parameters:

  • element (String) (defaults to: nil)

    The XML element to use.

  • attributes (String: String) (defaults to: {})

    Any attributes that should be set on the header.



24
25
26
27
# File 'lib/xliff/header.rb', line 24

def initialize(element: nil, attributes: {})
  @element = element
  @attributes = attributes.transform_values(&:to_s)
end

Instance Attribute Details

#attributesHash<String, String> (readonly)

This header’s element

Returns:

  • (Hash<String, String>)


16
17
18
# File 'lib/xliff/header.rb', line 16

def attributes
  @attributes
end

#elementString (readonly)

This header’s element

Returns:

  • (String)


12
13
14
# File 'lib/xliff/header.rb', line 12

def element
  @element
end

Class Method Details

.from_xml(xml) ⇒ Header

Decode the given XML into an Xliff::Header object, if possible

Raises for invalid input.

Parameters:

Returns:



56
57
58
59
60
61
62
63
64
# File 'lib/xliff/header.rb', line 56

def self.from_xml(xml)
  raise 'Header XML is nil' if xml.nil?
  raise "Invalid Header XML – must be a nokogiri object, got `#{xml.class}`" unless xml.is_a? Nokogiri::XML::Element

  Header.new(
    element: xml.name,
    attributes: xml.keys.to_h { |k| [k, xml[k]] }
  )
end

Instance Method Details

#to_sString

Encode this Xliff::Header object to an XML string

Returns:

  • (String)


46
47
48
# File 'lib/xliff/header.rb', line 46

def to_s
  to_xml.to_xml
end

#to_xmlNokogiri::XML.fragment

Encode this Xliff::Header object as an Nokogiri XML Element Representation of this header’s expected element

Returns:



32
33
34
35
36
37
38
39
40
41
# File 'lib/xliff/header.rb', line 32

def to_xml
  fragment = Nokogiri::XML.fragment('')
  node = fragment.document.create_element(@element)

  @attributes.each do |key, value|
    node[key] = value
  end

  node
end