How to set content type for temporary file

I have a rake task that retrieves XML documents and stores them in a model in my application. The task worked until I added a content_type model check on the model

Now the task causes an error:

Datafile content type is invalid, Datafile is invalid

How to set the ttext file content_type in text / xml so that the check passes?

Task code below:

  task :fetch_documents => :environment do        
    Net::FTP.open("www.example.com", "xxxxx", "xxxxx") do |ftp|          
      ftp.nlst.each do |file_name|
        tmp = Tempfile.new(['foo', '.xml' ])
        ftp.gettextfile(file_name, tmp.path)
        # save it
        document = Document.new
        document.file_name = File.basename(file_name)
        document.datafile = tmp
        document.save!
        tmp.close
        end
     end
  end
+3
source share
1 answer

I managed to find the type of content that will be used as follows:

gem install mime-types

and added to my rake task:

require 'mime/types' 

Then I burst into the subtitle and used

MIME::Types.type_for(tmp.path).first.content_type 

which allowed me to add the correct mime type to the model check:

application/xml

I'm not sure why the files are / xml application, when the loaded forms are text / xml, but in retrospect, a pretty obvious fix!

+1

All Articles