Unexpected behaviour with a file in Ruby on Rails - ruby

While trying to upload a file in Ruby on Rails, I ran into an issue.
Here is how I upload a file:
def upload_image(image)
File.new(Rails.root.join('assets','images','products',image.original_filename),'wb') do |f|
f.write(image.read)
end
end
Which throws an exception:
Errno::ENOENT in ProductsController#update
No such file or directory - /home/alex/RubymineProjects/psg/assets/images/products/my-image.png
Why is this happening? I'm just creating a new file, I'm not trying to open an existing one.

It does not create directories.
File.new("test", 'wb') #=> creates the file test
File.new("test/test", 'wb') #=> test.rb:1:in `initialize': No such file or directory - test/test (Errno::ENOENT)
If you add an /app you have the path you are looking for. Don't really think thats the way to use the asset pipeline though. See reasoning in this question.
File.open(Rails.root.join('app','assets','images','test.jpg'),'wb') do |f|
f.write("image")
end
=> 5
cat app/assets/images/test.jpg #=> image%

Related

Creating a simple csv file: No such file or directory # rb_sysopen (Errno::ENOENT)

I am struggling with a very basic task of creating a csv file from the ruby core library. I am basically copying the code almost exactly:
require 'csv'
CSV.open("~/Desktop/codes.csv", "wb") do |csv|
csv << ["id", "code"]
csv << ["TESTCODE01", "CODE001"]
end
And when I execute this code, I receive the following error:
csv.rb:641:in `initialize': No such file or directory # rb_sysopen - ~/Desktop/codes.csv (Errno::ENOENT)
I have an empty csv file that I'm trying to write to on my Desktop but somehow it errors out. I know this has to be something simple that I'm not doing. Can someone point out what Im doing wrong? Thank you.
You're expecting something like shell expansion but you're not running in a shell. Instead do something on the order of:
require 'csv'
CSV.open(Dir.home + "/Desktop/codes.csv", "wb") do |csv|
csv << ["id", "code"]
csv << ["TESTCODE01", "CODE001"]
end

No such file or directory # rb_sysopen ruby and csv

First of all I would like to say that I'm new to Ruby and if I'm not able to give you a good picture of what I'm trying to solve, that is the reason.
I'm trying to convert URLs into images and I've looked around for answers but I can't seem to find an answer that works for me. The file has around 70,000+ links and I'm also trying to name these at the same time. I'm using ruby 2.3.0 if that is relevant.
Code --
require 'open-uri'
require 'tempfile'
require 'uri'
require 'csv'
def downloadFile(path,url)
begin
open(path, "wb+") do |file|
file << open(url).read
end
return true
rescue
return false
end
end
puts Dir.pwd
CSV.foreach("C/Users/b40ssr/RubymineProjects/Bygma/convert/konvertera.CSV", headers:true) do |row|
downloadFile(row[0], row[1])
end
So the error that I'm getting is
C:/Ruby23/lib/ruby/2.3.0/csv.rb:1265:in `initialize': No such file or directory # rb_sysopen - C/Users/b40ssr/RubymineProjects/Bygma/convert/konvertera.CSV (Errno::ENOENT)
I understand that there is something wrong with the directory but I cant seem to figure out what it is.
First of all, you can use relative path or just use "C:/"
Second, You are trying to open each row of CSV file ??
CSV.foreach("C/Users/b40ssr/RubymineProjects/Bygma/convert/konvertera.CSV"). This will iterate over each rows in CSV file.
Do you want to open each CSV file inside a directory ??

Ruby: cannot load such file - LoadError

I got this 'require' cannot load such file error.
I got this previously and I added
__LIB_DIR__ = File.expand_path(File.join(File.dirname(__FILE__), ".."))
unless $LOAD_PATH.include?(__LIB_DIR__)
$LOAD_PATH.unshift(__LIB_DIR__)
end
I would like to know what this does? I added this in a main 'require' file of my project.
Now I write a test case,
$:.unshift File.join(File.dirname(__FILE__), ".")
I try to run it, I get the LoadError. I also tried require_relative no luck.
Structure:
Main
Git
lib
files.rb
base.rb
test
test1.rb
I have the first code block above in base.rb where I do all 'requires'
and when i try to run the test. I get LoadError.
'Please',Explain the first and second code blocks also give me a solution
For clarity, instead of
__LIB_DIR__ = File.expand_path(File.join(File.dirname(__FILE__), ".."))
use
__LIB_DIR__ = File.expand_path('..', File.dirname(__FILE__))
What does this do?
unless $LOAD_PATH.include?(__LIB_DIR__)
$LOAD_PATH.unshift(__LIB_DIR__)
end
Consider this:
ary = %w[a b]
ary # => ["a", "b"]
ary.unshift('c')
ary # => ["c", "a", "b"]
I try to run it, I get the LoadError. I also tried require_relative no luck.
That could be for a number of reasons, but, unfortunately you didn't share the code where it occurs. require and require_relative are both used to load code, but have different syntax in the parameter passed. We'd need to know what you're trying to load, and where it is in the file hierarchy in relation to your calling script.
Perhaps one of these, or their related questions, would help:
"ruby `require': cannot load such file"
"Ruby 'require' error: cannot load such file"
"require cannot load such file"
"Cannot load files using require"

how to read file using path in ruby by function IO.readlines("path")[0]

i want to read first line of file by using following function in ruby
IO.readlines("path")[0]
But file is not in current directory, so i use path there
puts IO.readlines("Home/Documents/vikas/SHIF.doc")
but it is giving error as
a1.rb:1:in `readlines': No such file or directory # rb_sysopen - Home/Documents/vikas/SHIF.doc (Errno::ENOENT)
from a1.rb:1:in `<main>'
You can also open a file and read only the first line instead of the entire file
File.open("Home/Documents/vikas/SHIF.doc").readline
You can use File.expand_path:
puts IO.readlines(File.expand_path("Home/Documents/vikas/SHIF.doc", __FILE__))
Note however that it will create path relatively to a file directory, not to a root directory.
If you are using rails, you could use:
puts IO.readlines(Rails.root.join 'Home', 'Documents', 'vikas', 'SHIF.doc')

How do open a file for writing only if it doesn't already exist in ruby

I want to open a file for writing but only if it doesn't already exist. If the file exists I want to raise an exception. Is this the best way to do it?
filename = 'foo'
raise if File.exists? filename
File.open(filename, 'w') do |file|
file.write contents
end
What is the most idiomatic way to do this without the race condition?
After doing some further research, it seems you can use the File::CREAT and File::EXCL mode flags.
filename = 'foo'
File.open(filename, File::WRONLY|File::CREAT|File::EXCL) do |file|
file.write contents
end
In this case, open will raise an exception if the file exists. After running once, this program succeeds without error, creating a file named foo. On the second run, the program emits this:
foo.rb:2:in `initialize': File exists - foo (Errno::EEXIST)
from foo.rb:2:in `open'
from foo.rb:2
From man open:
O_WRONLY open for writing only
O_CREAT create file if it does not exist
O_EXCL error if O_CREAT and the file exists

Resources