Search code examples
rubyruby-on-rails-3fileopen-uri

Stop file write if file size exceeds 500KB ruby on rails


How can I stop file writing ( upload form remote url ) when file size exceeds 500KB ?

I am using following code to upload a remote file

require 'open-uri'
open('temp/demo.doc', 'wb') do |file|
  file << open('http://example.com/demo.doc').read
end

this code is working properly and I am able to get files in temp folder. Now I want if filesize exceeds 500KB then it should stop writing file. In other words I want only 500KB of file if it is more than 500KB


Solution

  • IO#read, takes a bytes argument, so you can specify the size of what you want to read from IO as below:

    require 'open-uri'
    open('temp/demo.doc', 'wb') do |file|
      file << open('http://example.com/demo.doc').read(500000)
    end
    

    you can also play with things like file.stat.size but given you are piping directly to file you would have to do more things to get this to work.