Read contents of a local file into a variable in Rails

Ruby on-RailsRuby

Ruby on-Rails Problem Overview


All I want to do is get all the content from a local file and store it in a variable. How?

File.read(@icon.full_filename).each {|l| r += l}

only gives me a part of it. In PHP, I just used file_get_contents.

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

data = File.read("/path/to/file")

Solution 2 - Ruby on-Rails

I think you should consider using IO.binread("/path/to/file") if you have a recent ruby interpreter (i.e. >= 1.9.2)

You could find IO class documentation here http://www.ruby-doc.org/core-2.1.2/IO.html

Solution 3 - Ruby on-Rails

Answering my own question here... turns out it's a Windows only quirk that happens when reading binary files (in my case a JPEG) that requires an additional flag in the open or File.open function call. I revised it to open("/path/to/file", 'rb') {|io| a = a + io.read} and all was fine.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionStevenView Question on Stackoverflow
Solution 1 - Ruby on-Railszed_0xffView Answer on Stackoverflow
Solution 2 - Ruby on-RailsMehdiView Answer on Stackoverflow
Solution 3 - Ruby on-RailsStevenView Answer on Stackoverflow