Published on

Create a file and all the folder structure

  • avatar
    Carlos Baraza
    I write software and other philosophical stuff.

Today I had to deal with a small problem in Rails 2.3.18. It was how to receive on an API a XML file via JSON with the content of the file in Base64. In order to complete the task, I had to create the file, decode the content, write it in the file and move the file to another folder.

To create the file in "{{RAILSROOT}}/tmp/aaa/", first we have to create the folder structure:

file_dir = Rails.root.join(['tmp', 'aifmd', 'received_files'])

mkdir_p will create all the folder structure if the folders do not exists yet.

Then, to create the file, we give it a name. In my case, just the current time in iso8601 format. We need to get rid of the colons (:), as they are not allowed as a character for a file name.

# The parameter to iso8601 give you the number of decimals. To reduce possible collisions, I gave it 2 decimals.
file_name = "#{':','')}.xml"
# Open a new file with writing rights
file_path = [file_dir, file_name].join('/')
tmp_file =, 'w+')
# Write on the file the decoded content of the xml.
decoded_file_content = Base64.decode64(params[:file_content])