Skip to content

Instantly share code, notes, and snippets.

@swistak
Last active July 3, 2018 03:36
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save swistak/4622792 to your computer and use it in GitHub Desktop.
Save swistak/4622792 to your computer and use it in GitHub Desktop.
Generates objects for use with Savon. Uses Action Model (ServiceBase) to provide validations and attributes access, but can be easily adapted to Struct / OpenStruct if needed.
module MyModule
# Regenerating code
end unless __FILE__ == $0
if __FILE__ == $0
require 'savon'
split_on = "#" + " Regenerating code"
code = File.read(__FILE__).split(split_on).last
wsdl_file_path = File.join(File.dirname(__FILE__), ARGV.first || raise("Gimme file!"))
client = Savon.client(wsdl_file_path)
wsdl = client.wsdl
output = [
"# Authomatically generated from WSDL. Use bundle exec objects.rb to regenerate",
"",
"module MyModule"
]
wsdl.parser.xpath("//xs:complexType[@name]").each do |complex_type|
name = complex_type["name"]
parent = complex_type.xpath('.//xs:extension', "xs" => "http://www.w3.org/2001/XMLSchema").first
parent = parent ? parent["base"].split(":").last : "ServiceBase"
output << " class #{ name } < #{parent}"
to_validate = []
complex_type.xpath('.//xs:element', "xs" => "http://www.w3.org/2001/XMLSchema").each do |element|
a = element.attributes.dup
name = a.delete("name").value
type = a.delete("type").value.split(":").last
minO = a.delete("minOccurs")
maxO = a.delete("maxOccurs")
required = minO ? minO.value.to_i : 0
p a.keys unless a.empty?
output << " # %-40s : %-40s" % [name, type]
to_validate << " validates :#{name}, :presence => true" if required > 0
end
output << ""
output += to_validate
output << " end\n"
end
output << "\n"
output << split_on
output << code.strip
File.open(__FILE__, "w"){|f| f.write(output.join("\n")) }
end
@jasonm23
Copy link

Nice work.

@adam-koblentz
Copy link

I'm trying to use this module, and I'm getting just a bunch of ["nillable"] instead of objects.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment