Creating an XML to Hash converter in Ruby
Disclaimer: This is my second time writing anything in Ruby. I might not be doing it the ‘right way’ or anything. Am just having fun but am more than happy to accept corrections and advice. I am doing this as I go, so expect a lot of edits.
So, why an XML to hash converter? I have no freaking idea! I was just bored an needed something to do.
This goes without saying that you’ll need Ruby installed in your machine. Here’s a tutorial on how to do it on Ubuntu. On windows, it’s as easy as downloading and clicking next-next-next. You can download Ruby here.
After making sure your Ruby setup is okay, open your terminal and create a new folder. If you’re using Windows on this one like me, you can use Git Bash. Seeing as I am a cool and awesome person, I am calling my project Hashr.
Inside the folder, run:
$gem install bundler
$gem install activesupport
Create a new file and name it. Am calling mine Hashr.rb
Before continuing, make sure you have a .xml file in the same project folder for testing your work. I am using an XML of Shakespeare’s Macbeth.
First, I’ll call the activesupport library.
Then, I’ll ask the user for a file name and store it inside a global variable.
#load requirements
require 'active_support/core_ext/hash'
STDOUT.sync = true
puts "Hashr Needs some xmls to convert"
puts "what is your filename"
#get filename from user
$file_name = STDIN.gets.chomp
So far, my converter only works on XML files. I’ll add code to check for file extensions and store that extension in a variable.
#get extension of given file name
extension = File.extname($file_name)
I will then define a conditional statement that proceeds to hash the file if the extension is a .xml and gives an error for any other extension.
if extension == '.xml'
puts "You have loaded a "+extension+" file"
def converter
file_data = File.open($file_name)
hashr = Hash.from_xml(file_data)
puts hashr
end
puts converter
else
puts "the extension "+extension+" is not a supported format"
end
The whole code bit look like:
To run the script, got to your terminal and run
$ruby <filename.rb>
The next update will have code to write the hash into a file.
All code used in this article can be found in this Github repo.