Class: Atom::Content::Html

Inherits:
Base show all
Defined in:
lib/atom.rb

Overview

Html content within an Atom document.

Instance Method Summary collapse

Methods inherited from Base

#==

Methods included from Xml::Parseable

#==, #accessor_name, #current_node_is?, included, #next_node_is?, #parse

Methods inherited from String

#constantize, #demodulize, #singularize

Constructor Details

#initialize(o) ⇒ Html

Creates a new Content::Html.

o

An XML::Reader or a HTML string.



263
264
265
266
267
268
269
270
271
272
273
274
# File 'lib/atom.rb', line 263

def initialize(o)
  case o
  when XML::Reader
    super(o.read_string)
    parse(o, :once => true)
  when String
    super(o)
    @type = 'html'
  else
    raise ArgumentError, "Got #{o} which isn't a String or XML::Reader"
  end        
end

Instance Method Details

#to_xml(nodeonly = true, name = 'content', namespace = nil, namespace_map = Atom::Xml::NamespaceMap.new) ⇒ Object

:nodoc:



276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
# File 'lib/atom.rb', line 276

def to_xml(nodeonly = true, name = 'content', namespace = nil, namespace_map = Atom::Xml::NamespaceMap.new) # :nodoc:
  # Reject content that isn't UTF-8. If we don't check libxml just
  # fails silently and outputs the content element without any content. At
  # least checking here and raising an exception gives the caller a chance
  # to try and recitfy the situation.
  #

  if RUBY_VERSION =~ /^1.8/
    require 'iconv'
    # Convert from utf-8 to utf-8 as a way of making sure the content is
    # UTF-8.
    begin
      node = XML::Node.new("#{namespace_map.prefix(Atom::NAMESPACE, name)}")
      node << Iconv.iconv('utf-8', 'utf-8', self.to_s).first
      node['type'] = 'html'
      node['xml:lang'] = self.xml_lang if self.xml_lang
      node
    rescue Iconv::IllegalSequence => e
      raise SerializationError, "Content must be converted to UTF-8 before attempting to serialize to XML: #{e.message}."
    end

  else
    self_string = self.to_s

    if self_string.dup.force_encoding("UTF-8").valid_encoding?
      node = XML::Node.new("#{namespace_map.prefix(Atom::NAMESPACE, name)}")
      node << self_string
      node['type'] = 'html'
      node['xml:lang'] = self.xml_lang if self.xml_lang
      node
    else
      raise SerializationError, "Content must be converted to UTF-8 before attempting to serialize to XML: #{self}."
    end
  end
end