Created
July 18, 2018 18:07
-
-
Save barbolo/51bf24c3ea5b5c27c42e3ac005831484 to your computer and use it in GitHub Desktop.
Render a post with libxml in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Renderer::Post | |
def self.create_doc_xml(root) | |
doc = LibXML::XML::Document.new | |
doc.encoding = LibXML::XML::Encoding::UTF_8 | |
doc.root = LibXML::XML::Node.new(root) | |
doc | |
end | |
def self.create_node(name, value=nil, type=nil) | |
node = LibXML::XML::Node.new(name) | |
node.content = value.to_s unless value.nil? | |
LibXML::XML::Attr.new(node, 'type', type) unless type.nil? | |
node | |
end | |
def self.xml(post) | |
doc = create_doc_xml('post') | |
doc.root << create_node('content', post.content.to_s) | |
doc.root << create_node('created-at', post.created_at.iso8601, 'dateTime') | |
doc.root << create_node('published', post.published.to_s, 'boolean') | |
# author | |
doc.root << (author = create_node('author')) | |
author << create_node('name', post.author.name.to_s) | |
author << create_node('age', post.author.age.to_s, 'integer') | |
author << create_node('email', post.author.email.to_s) | |
# comments | |
doc.root << (comments = create_node('comments', nil, 'array')) | |
post.comments.each do |comment| | |
comments << (node_comment = create_node('comment')) | |
node_comment << create_node('created-at', comment.created_at.iso8601, 'dateTime') | |
node_comment << create_node('message', comment.message) | |
# user | |
node_comment << (user = create_node('user')) | |
user << create_node('name', comment.user.name.to_s) | |
user << create_node('age', comment.user.age.to_s, 'integer') | |
user << create_node('email', comment.user.email.to_s) | |
node_comment << create_node('attachment', comment.attachment) | |
end | |
doc.to_s | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment