Skip to content

Instantly share code, notes, and snippets.

@AAlvarez90
Last active April 28, 2016 19:31
Show Gist options
  • Save AAlvarez90/9934e9de98522677a6e51fc256068f69 to your computer and use it in GitHub Desktop.
Save AAlvarez90/9934e9de98522677a6e51fc256068f69 to your computer and use it in GitHub Desktop.
Helper function for REXML to create an element and pass in text and attribute at once.
#Method
def create_element(name, content, attributes = {})
element = Element.new name
if content.is_a? Array
content.each { |e|
element.elements << e
}
else
(element.text = content) unless(content.nil?)
end
if !attributes.empty?
attributes.each_pair { |(key, value)|
element.add_attribute(key, value)
}
end
return element
end
#long way
element = Element.new 'timestamp'
element.add_text '2pm'
element.add_attribute 'smlns:o', 'http://somewhere.in.the.web'
element.add_attribute 'Id', '12'
element2 = Element.new 'information'
element2.add_text 'dffdfdfdfdf'
element2.add_attribute 'smlns:o', 'http://somewhere.in.the.web'
element2.add_attribute 'Id', '12'
element_parent = Element.new 'parent'
element_parent.add_attribute 'smlns:o', 'http://somewhere.in.the.web'
element_parent.add_attribute 'Id', '12'
element_parent.elements << element
element_parent.elements << element2
#New way
element = create_element("timestamp",'2 pm', {'smlns:o' => 'http://somewhere.in.the.web', 'Id' => '12'})
element2 = create_element("information",'dffdfdfdfdf', {'smlns:o' => 'http://somewhere.in.the.web', 'Id' => '12'})
element_parent = create_element("parent", [element, element2], {'smlns:o' => 'blahblah', 'Id' => '12'})
puts element_parent
#Outputs
#<parent Id='12' smlns:o='blahblah'><timestamp Id='12' smlns:o='http://somewhere.in.the.web'>2 pm</timestamp><information Id='12' smlns:o='http://somewhere.in.the.web'>dffdfdfdfdf</information></parent>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment