Sha256: a4cd6e64827a87752535bb754137c287e145f6a30073ac870a7239fb94013219

Contents?: true

Size: 1.55 KB

Versions: 1

Compression:

Stored size: 1.55 KB

Contents

require 'xmlsimple'
require 'yaml'
require 'fileutils'

default_output_file = 'output.yml'

# Create file if not present. If present but different give warning
def create_file(options)
  filename = options[:filename]
  raise 'Need to pass filename' unless filename
  content = options[:content]
  raise 'Need to pass contents to insert into file' unless content
  if File.exist? filename
    old_content = File.read(filename)
    if old_content != content
      warn "!! #{filename} already exists and differs from template"
    end
  else
    File.open(filename, 'w') do |f|
      f.puts content
    end
    puts 'Created: ' + filename
  end
end

# Convert key in camelcase to underscore separated (snakecase)
def underscore_key(key)
  key.to_s.gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2')
    .gsub(/([a-z\d])([A-Z])/,'\1_\2')
    .tr('-', '_')
    .gsub(/\s/, '_')
    .gsub(/__+/, '_')
    .downcase
end

# For all keys in a Hash, convert Camelcase to underscore separated
def convert_hash_keys(value)
  case value
    when Array
      value.map { |v| convert_hash_keys(v) }
    when Hash
      Hash[value.map { |k, v| [underscore_key(k), convert_hash_keys(v)] }]
    else
      value
  end
end

if ARGV[0]
  warn "Using '#{default_output_file}' as default output file since no 2nd argument passed" unless ARGV[1]
  hash = XmlSimple.xml_in(ARGV[0])
  converted = convert_hash_keys hash
  create_file(filename: ARGV[1] || default_output_file, content: converted.to_yaml)
else
  puts 'usage: xml_to_yaml_file [input.xml] [output.yml] '
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
soaspec-0.0.13 exe/xml_to_yaml_file