utime permission denied in windows 7 when call FileUtils.touch(f) - ruby

I'm working with ruby 2.0 on windows 7 (unfortunately I have to) and have issue with this code:
FileUtils.touch(file)
This code is needed to update file.ctime (which probably will have problems too)
So, when files is processed I 'touch' them and not processing them in next iteration.
How can I deal with it error?
ruby_path/fileutils.rb:1137:in 'utime': Permission denied 'path_to_file' Errno::EACCES
'block in touch'
'each'
'touch'
example:
file = File.new('file_path')
FileUtils.mkdir_p(path)
FileUtils.cp(file.path, path)
FileUtils.touch(file)

I tested with ruby 1.9 and 2.0. FileUtils.touch works without problems.
Can you provide a MWE. Did you check the permissions on the file you want to check.
Especially: Are you sure, you don't touch a directory?
If you don't want to check for directories, you may extend FileUtils by FileUtils.save_touch:
require 'fileutils'
module FileUtils
def self.save_touch(fpath)
FileUtils.touch(fpath) unless File.directory?(fpath)
end
end
FileUtils.save_touch(Dir.pwd)
After update of question:
FileUtils.touch has one parameter: a file name or path to a file.
You have to adapt your example:
file = File.new('file_path')
FileUtils.mkdir_p(path)
FileUtils.cp(file.path, path)
FileUtils.touch(file.path)

Related

Failed to run a very simple ruby script [duplicate]

This question already has answers here:
Ruby: how to "require" a file from the current working dir?
(5 answers)
Closed 6 years ago.
I have create a Ruby class Worker, file name is Worker.rb:
class Worker
def initialize
...
end
def doTask(task_name)
...
end
end
Then, I created another Ruby script file, named run.rb (it requires Worker):
require 'Worker'
worker = Worker.new
worker.doTask("sort")
Both two ruby files are located directly under the project folder:
ProjectFolder/
-- Worker.rb
-- run.rb
I run the run.rb under project folder by command:
ruby run.rb
But get following error:
/Users/John/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require': cannot load such file -- Worker (LoadError)
from /Users/John/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from runme.rb:1:in `<main>'
Why?
I figured out after checking #Geo 's github project, I should use:
require_relative "worker"
require looks for the required file from the so called load path and not the current directory. Since the syntax for looking in the current directory was awkward Ruby 1.9 introduces require_relative, which looks in the current directory.
Change your code like this:
require_relative "Worker"
instead of
require "Worker"
The reason this does not work is because the current directory is not part of ruby's default load path.
If you run the following command, you will see what the current load path is and it will confirm that the current directory is not part of that path.
ruby -e 'puts $LOAD_PATH'
This should answer your primary question as to why the required file was not loaded.
As for a solution, require_relative will work and is probably the best solution in this case.
There are however still cases were inserting directories into the load path is helpful, if not required. For example say you have a script that can be run anywhere in the file system and you want the flexibility to require a particular version of your co-worker's foo class.
/afs/some_cell/u/john/some_ruby_lib
prod/
foo.rb
bar.rb
prev/
foo.rb
bar.rb
beta/
foo.rb
bar.rb
In a case like this either setting the RUBYSIM var (maybe in a wrapper) or setting the proper include path on the ruby command line can be a useful solution.
Again, your co-worker has not published this as a gem, he is just providing a shared directory.
There are several ways you can insert directories into the load path when it is appropriate, as demonstrated below:
You can use the -I command line flag
ruby -I some_path -e 'puts $LOAD_PATH'
You can set the RUBYLIB env var to include your current directory.
on unix/linix/osx
export RUBYLIB=some_path
on windows
set RUBYLIB=some_path

Ruby Project - Prevent a ruby file from directly being called from OS command line

I am doing a demo command line project in Ruby. The structure is like this:
/ROOT_DIR
init.rb
/SCRIPT_DIR
(other scripts and files)
I want users to only go into the application using init.rb, but as it stands, anyone can go into the sub-folder and call other ruby scripts directly.
Questions:
What ways can above scenario be prevented?
If I was to use directory permissions, would it get reset when running the code from a Windows machine to on Linux machine?
Is there anything that can be included in Ruby files itself to prevent it from being directly called from OS command line?
You can't do this with file permissions, since the user needs to read the files; removing the read permission means you can't include it either. Removing the execute permission is useful to signal that these file aren't intended to be executed, but won't prevent people from typing ruby incl.rb.
The easiest way is probably to set a global variable in the init.rb script:
#!/usr/bin/env ruby
FROM_INIT = true
require './incl.rb'
puts 'This is init!'
And then check if this variable is defined in the included incl.rb file:
unless defined? FROM_INIT
puts 'Must be called from init.rb'
exit 0
end
puts 'This is incl!'
A second method might be checking the value of $PROGRAM_NAME in incl.rb; this stores the current program name (like argv[0] in many other languages):
unless $PROGRAM_NAME.end_with? 'init.rb'
puts 'Must be called from init.rb'
exit 0
end
I don't recommend this though, as it's not very future-proof; what if you want to rename init.rb or make a second script?

Ruby 'require' error: cannot load such file

I've one file, main.rb with the following content:
require "tokenizer.rb"
The tokenizer.rb file is in the same directory and its content is:
class Tokenizer
def self.tokenize(string)
return string.split(" ")
end
end
If i try to run main.rb I get the following error:
C:\Documents and Settings\my\src\folder>ruby main.rb
C:/Ruby193/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require': cannot load such file -- tokenizer.rb (LoadError)
from C:/Ruby193/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require '
from main.rb:1:in `<main>'
I just noticed that if I use load instead of require everything works fine. What may the problem be here?
I just tried and it works with require "./tokenizer".
Just do this:
require_relative 'tokenizer'
If you put this in a Ruby file that is in the same directory as tokenizer.rb, it will work fine no matter what your current working directory (CWD) is.
Explanation of why this is the best way
The other answers claim you should use require './tokenizer', but that is the wrong answer, because it will only work if you run your Ruby process in the same directory that tokenizer.rb is in. Pretty much the only reason to consider using require like that would be if you need to support Ruby 1.8, which doesn't have require_relative.
The require './tokenizer' answer might work for you today, but it unnecessarily limits the ways in which you can run your Ruby code. Tomorrow, if you want to move your files to a different directory, or just want to start your Ruby process from a different directory, you'll have to rethink all of those require statements.
Using require to access files that are on the load path is a fine thing and Ruby gems do it all the time. But you shouldn't start the argument to require with a . unless you are doing something very special and know what you are doing.
When you write code that makes assumptions about its environment, you should think carefully about what assumptions to make. In this case, there are up to three different ways to require the tokenizer file, and each makes a different assumption:
require_relative 'path/to/tokenizer': Assumes that the relative path between the two Ruby source files will stay the same.
require 'path/to/tokenizer': Assumes that path/to/tokenizer is inside one of the directories on the load path ($LOAD_PATH). This generally requires extra setup, since you have to add something to the load path.
require './path/to/tokenizer': Assumes that the relative path from the Ruby process's current working directory to tokenizer.rb is going to stay the same.
I think that for most people and most situations, the assumptions made in options #1 and #2 are more likely to hold true over time.
Ruby 1.9 has removed the current directory from the load path, and so you will need to do a relative require on this file, as David Grayson says:
require_relative 'tokenizer'
There's no need to suffix it with .rb, as Ruby's smart enough to know that's what you mean anyway.
require loads a file from the $LOAD_PATH. If you want to require a file relative to the currently executing file instead of from the $LOAD_PATH, use require_relative.
I would recommend,
load './tokenizer.rb'
Given, that you know the file is in the same working directory.
If you're trying to require it relative to the file, you can use
require_relative 'tokenizer'
I hope this helps.
Another nice little method is to include the current directory in your load path with
$:.unshift('.')
You could push it onto the $: ($LOAD_PATH) array but unshift will force it to load your current working directory before the rest of the load path.
Once you've added your current directory in your load path you don't need to keep specifying
require './tokenizer'
and can just go back to using
require 'tokenizer'
This will work nicely if it is in a gem lib directory and this is the tokenizer.rb
require_relative 'tokenizer/main'
For those who are absolutely sure their relative path is correct, my problem was that my files did not have the .rb extension! (Even though I used RubyMine to create the files and selected that they were Ruby files on creation.)
Double check the file extensions on your file!
What about including the current directory in the search path?
ruby -I. main.rb
I used jruby-1.7.4 to compile my ruby code.
require 'roman-numerals.rb'
is the code which threw the below error.
LoadError: no such file to load -- roman-numerals
require at org/jruby/RubyKernel.java:1054
require at /Users/amanoharan/.rvm/rubies/jruby-1.7.4/lib/ruby/shared/rubygems/custom_require.rb:36
(root) at /Users/amanoharan/Documents/Aptana Studio 3 Workspace/RubyApplication/RubyApplication1/Ruby2.rb:2
I removed rb from require and gave
require 'roman-numerals'
It worked fine.
The problem is that require does not load from the current directory. This is what I thought, too but then I found this thread. For example I tried the following code:
irb> f = File.new('blabla.rb')
=> #<File:blabla.rb>
irb> f.read
=> "class Tokenizer\n def self.tokenize(string)\n return string.split(
\" \")\n end\nend\n"
irb> require f
LoadError: cannot load such file -- blabla.rb
from D:/dev/Ruby193/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `req
uire'
from D:/dev/Ruby193/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `req
uire'
from (irb):24
from D:/dev/Ruby193/bin/irb:12:in `<main>'
As it can be seen it read the file ok, but I could not require it (the path was not recognized). and here goes code that works:
irb f = File.new('D://blabla.rb')
=> #<File:D://blabla.rb>
irb f.read
=> "class Tokenizer\n def self.tokenize(string)\n return string.split(
\" \")\n end\nend\n"
irb> require f
=> true
As you can see if you specify the full path the file loads correctly.
First :
$ sudo gem install colored2
And,you should input your password
Then :
$ sudo gem update --system
Appear
Updating rubygems-update
ERROR: While executing gem ... (OpenSSL::SSL::SSLError)
hostname "gems.ruby-china.org" does not match the server certificate
Then:
$ rvm -v
$ rvm get head
Last
What language do you want to use?? [ Swift / ObjC ]
ObjC
Would you like to include a demo application with your library? [ Yes / No ]
Yes
Which testing frameworks will you use? [ Specta / Kiwi / None ]
None
Would you like to do view based testing? [ Yes / No ]
No
What is your class prefix?
XMG
Running pod install on your new library.
you need to give the path.
Atleast you should give the path from the current directory. It will work for sure.
./filename

Using yaml files within gems

I'm just working on my first gem (pretty new to ruby as well), entire code so far is here;
https://github.com/mikeyhogarth/tablecloth
One thing I've tried to do is to create a yaml file which the gem can access as a lookup (under lib/tablecloth/yaml/qty.yaml). This all works great and the unit tests all pass, hwoever when I build and install the gem and try to run under irb (from my home folder) I am getting;
Errno::ENOENT: No such file or directory - lib/tablecloth/yaml/qty.yaml
The code is now looking for the file in ~/lib/tablecloth... rather than in the directory the gem is installed to. So my questions are;
1) How should i change line 27 of recipe.rb such that it is looking in the folder that the gem is installed to?
2) Am I in fact approaching this whole thing incorrectly (is it even appropriate to use static yaml files within gems in this way)?
Well first of all you should refer to the File in the following way:
file_path = File.join(File.dirname(__FILE__),"yaml/qty.yaml")
units_hash = YAML.load_file(filepath)
File.dirname(__FILE__) gives you the directory in which the current file (recipe.rb) lies.
File.join connects filepaths in the right way. So you should use this to reference the yaml-file relative to the recipe.rb folder.
If using a YAML-file in this case is a good idea, is something which is widely discussed. I, myself think, this is an adequate way, especially in the beginning of developing with ruby.
A valid alternative to yaml-files would be a rb-File (Ruby Code), in which you declare constants which contain your data. Later on you can use them directly. This way only the ruby-interpreter has to work and you save computing time for other things. (no parser needed)
However in the normal scenario you should also take care that reading in a YAML file might fail. So you should be able to handle that:
file_path = File.join(File.dirname(__FILE__),"yaml/qty.yaml")
begin
units_hash = YAML.load_file(filepath)
rescue Psych::SyntaxError
$stderr.puts "Invalid yaml-file found, at #{file_path}"
exit 1
rescue Errno::EACCES
$stderr.puts "Couldn't access file due to permissions at #{file_path}"
exit 1
rescue Errno::ENOENT
$stderr.puts "Couldn't access non-existent file #{file_path}"
exit 1
end
Or if you don't care about the details:
file_path = File.join(File.dirname(__FILE__),"yaml/qty.yaml")
units_hash =
begin
YAML.load_file(filepath)
rescue Psych::SyntaxError, Errno::EACCES, Errno::ENOENT
{}
end

Rails irb default directory

I'm trying to include a source code file when I run irb but irb is unable to find it.
For example, say I am in the following directory in terminal:
/dan/rubyapp/
Assume I have a file named "firstapp.rb" in /dan/rubyapp/
I startup irb and from the irb prompt I type
> require "firstapp.rb"
but the file can't be found. If I type "Dir.pwd" it shows as
/dan/rubyapp/
The only way I can get "require" to work is if I include the full path like so
> require "/dan/rubyapp/firstapp.rb"
Is that the only way I can get this to work? All the tutorials I see online simply do "require file_name" so I assumed it would work.
here is the output from $: at irb
ruby-1.9.2-p0 > $:
=> ["/Users/Daniel/.rvm/gems/ruby-1.9.2-p0/gems/wirble-0.1.3/bin",
"/Users/Daniel/.rvm/gems/ruby-1.9.2-p0/gems/wirble-0.1.3/lib",
"/Users/Daniel/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/site_ruby/1.9.1",
"/Users/Daniel/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/site_ruby/1.9.1/x86_64-darwin10.4.0",
"/Users/Daniel/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/site_ruby",
"/Users/Daniel/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/vendor_ruby/1.9.1",
"/Users/Daniel/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/vendor_ruby/1.9.1/x86_64-darwin10.4.0",
"/Users/Daniel/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/vendor_ruby",
"/Users/Daniel/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1",
"/Users/Daniel/.rvm/rubies/ruby-
1.9.2-p0/lib/ruby/1.9.1/x86_64-darwin10.4.0"]
The problem is that the current working directory is no longer in your path (as of Ruby 1.9.2). There are a few different ways around the problem.
1) In a ruby file itself, you can use the method require_relative instead of require. This will load a file relative to the loaction of the file containing the require_relative method:
http://extensions.rubyforge.org/rdoc/classes/Kernel.html
require_relative 'firstapp.rb'
This, however, will not work in irb.
2) Your other option is to include the current path in your argument to the require method. This will work in irb or in a ruby file. For instance:
require './firstapp.rb'
The reason this was implemented in ruby was to avoid inadvertently requiring the wrong file if there are different files with the same name in different directories in the path (similar to how *nix does not include the current directory "." in its path)
A couple of things to try:
1) Drop the .rb from the end of your require so you have:
require 'firstapp'
You don't normally add the .rb to a require (only to a load) - have a look here for more details:
http://www.fromjavatoruby.com/2008/10/require-vs-load.html
2) Failing that, make sure the current directory is on your load path - in irb execute:
p $:
and it will print out your ruby load path - check for an entry for "." (mine is the last entry)

Resources