PageRenderTime 43ms CodeModel.GetById 35ms app.highlight 6ms RepoModel.GetById 1ms app.codeStats 0ms

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