/tools/Ruby/lib/ruby/1.8/wsdl/xmlSchema/xsd2ruby.rb

http://github.com/agross/netopenspace · Ruby · 107 lines · 84 code · 18 blank · 5 comment · 6 complexity · e890eea6dc931f1da6c2e5ee0cae7a41 MD5 · raw file

  1. # XSD4R - XSD to ruby mapping library.
  2. # Copyright (C) 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
  3. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can
  4. # redistribute it and/or modify it under the same terms of Ruby's license;
  5. # either the dual license version in 2003, or any later version.
  6. require 'xsd/codegen/gensupport'
  7. require 'wsdl/xmlSchema/importer'
  8. require 'wsdl/soap/classDefCreator'
  9. module WSDL
  10. module XMLSchema
  11. class XSD2Ruby
  12. attr_accessor :location
  13. attr_reader :opt
  14. attr_accessor :logger
  15. attr_accessor :basedir
  16. def run
  17. unless @location
  18. raise RuntimeError, "XML Schema location not given"
  19. end
  20. @xsd = import(@location)
  21. @name = create_classname(@xsd)
  22. create_file
  23. end
  24. private
  25. def initialize
  26. @location = nil
  27. @opt = {}
  28. @logger = Logger.new(STDERR)
  29. @basedir = nil
  30. @xsd = nil
  31. @name = nil
  32. end
  33. def create_file
  34. create_classdef
  35. end
  36. def create_classdef
  37. @logger.info { "Creating class definition." }
  38. @classdef_filename = @name + '.rb'
  39. check_file(@classdef_filename) or return
  40. write_file(@classdef_filename) do |f|
  41. f << WSDL::SOAP::ClassDefCreator.new(@xsd).dump
  42. end
  43. end
  44. def write_file(filename)
  45. if @basedir
  46. filename = File.join(basedir, filename)
  47. end
  48. File.open(filename, "w") do |f|
  49. yield f
  50. end
  51. end
  52. def check_file(filename)
  53. if @basedir
  54. filename = File.join(basedir, filename)
  55. end
  56. if FileTest.exist?(filename)
  57. if @opt.key?('force')
  58. @logger.warn {
  59. "File '#{filename}' exists but overrides it."
  60. }
  61. true
  62. else
  63. @logger.warn {
  64. "File '#{filename}' exists. #{$0} did not override it."
  65. }
  66. false
  67. end
  68. else
  69. @logger.info { "Creates file '#{filename}'." }
  70. true
  71. end
  72. end
  73. def create_classname(xsd)
  74. name = nil
  75. if xsd.targetnamespace
  76. name = xsd.targetnamespace.scan(/[a-zA-Z0-9]+$/)[0]
  77. end
  78. if name.nil?
  79. 'default'
  80. else
  81. XSD::CodeGen::GenSupport.safevarname(name)
  82. end
  83. end
  84. def import(location)
  85. WSDL::XMLSchema::Importer.import(location)
  86. end
  87. end
  88. end
  89. end