Skip to content

Instantly share code, notes, and snippets.

@kbni

kbni/queryxml.rb Secret

Last active January 17, 2016 00:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kbni/85c28e8d24a1007e4a86 to your computer and use it in GitHub Desktop.
Save kbni/85c28e8d24a1007e4a86 to your computer and use it in GitHub Desktop.
require 'xml/libxml'
# Generates 'QueryXML' for use with AutoTask Web Services API
module QueryXML
def _if(field_name, op, compare, udf = false)
f_xml = (XML::Node.new('field') << field_name)
f_xml << (e_xml = XML::Node.new('expression') << compare)
e_xml['op'] = op
f_xml['udf'] = true.to_s if udf
f_xml # return field comparison XML
end
def _or(*args)
o_xml = XML::Node.new('condition')
o_xml['operator'] = 'or'
args.each { |se| o_xml << se }
o_xml
end
def _and(*args)
o_xml = XML::Node.new('condition')
args.each { |se| o_xml << se }
o_xml
end
def queryxml(entity)
Query.new(entity)
end
# Storage object for our XML document
class Query
def initialize(entity)
n_entity = XML::Node.new('entity')
n_entity << entity
n_query = XML::Node.new('query')
@doc = XML::Document.new
@doc.root = XML::Node.new('queryxml')
@doc.root << n_entity
@doc.root << n_query
@query = n_query
end
def to_s
@doc.root.to_s(indent: true)
end
def <<(value)
@query << value
end
end
end
include QueryXML
q = queryxml('Ticket')
q << _if('id', 'equals', 1)
q << _or(
_and(
_or(
_if('id', 'greaterthan', 100),
_if('id', 'lessthan', 199)
),
_or(
_if('id', 'greaterthan', 200),
_if('id', 'lessthan', 299)
)
),
_and(
_if('udfField', 'equals', 200, true)
)
)
puts q.to_s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment