How to create a shortcut of a required function (`cp = FileUtils.cp`)? - ruby

I just want to call cp instead of FileUtils.cp. This is turning to be surprisingly hard to do in Ruby!
In Javascript this would simply be: cp = FileUtils.cp. This doesn't work in Ruby because its paren-less calling doesn't allow assigning this way (Ruby thinks I'm calling FileUtils.cp but I'm trying to assign it, I get the error: wrong number of arguments (given 0, expected 1) (ArgumentError)).
I tried alias but alias cp FileUtils.cp doesn't work because of the dot (I get the error: syntax error, unexpected '.', expecting end-of-input). alias_method would be for creating an alias within FileUtils, like FileUtils.cp2, but that's not what I want to do.
cp = FileUtils.method :cp works BUT my new shortcut is a "second-class" function, whenever I use it I have to call it as cp.call instead of just cp, thus reducing the brevity of my shortcut and forcing me to remember this new way of calling some functions.
Is there a way to simply get cp be FileUtils.cp? Thanks!

You can create a function in global space
def cp(src, dest, options = {})
FileUtils.cp(src, dest, options = {})
end

Related

shell cd command in Ruby

Im trying to execute shell commands using ruby, but i cant change directory to PATH with blank spaces.
variable = %x[cd #{ENV["HOME"]}/Virtual\\ VMs/]
This is not working.
Thank you
To be absolutely safe:
path = File.join [ENV["HOME"], 'Virtual VMs']
variable = %x[cd '#{path}']
Please note, that cd has empty output, so to make sure it works one probably wants to do smth like:
path = File.join [ENV["HOME"], 'Virtual VMs']
variable = %x[cd '#{path}' && ls -la]
#⇒ "total 32\ndrwxr-xr-x ....."
What is ist supposed to do? You try to chdir into a directory, but then don't do anything in it. Your variable will be empty in any case. Aside from the fact that it is pointless to do, you can not reliably execute a cd by itself in this way, because it is not an executable file. You can see this if you just execute %x[cd]. You will get an Errno::ENOENT exception.
Maybe you should first describe in a broader context, what you want to achieve with your code. Where would you like to change the working directory? Within the Ruby process - in which case you have to use Dir.chdir - or in the child process - in which case you have to execute some command after the cd.

Ruby mkdir returns 0

I have a Ruby script which sets up a directory which I need some other methods to use to store files. So, I need to be able to pass the directory as a string to some other methods:
To create the directory
results_dir = Dir.mkdir("/results/#{Time.now.strftime('%m-%d-%Y_%H:%M:%S')}")
The problem is that results_dir returns 0, not the string I would expect for the directory that was made: "/results/01-18-2016_14:58:38"
So, when I try to pass this to another method (i.e. my_method(var1, var2, results_dir), it's reading it as:
0/the_file_i_create
How can I pass the actual directory path to my methods?
It's not clear why you expect Dir.mkdir to return the directory name, since the docs explicitly say that Dir.mkdir returns 0:
mkdir( string [, integer] ) → 0
If you need the name of the directory you're creating, put it in a variable before you call Dir.mkdir:
results_dir = "/results/#{Time.now.strftime('%m-%d-%Y_%H:%M:%S')}"
Dir.mkdir(results_dir)
puts results_dir # => /results/01-18-2016_14:58:38
P.S. Avoid using colons (:) in file and directory names. It can cause issues on some systems, including OS X and Windows.

Show error message for every argument that is not defined in Ruby program

I'm creating a program in Ruby for replacing content of multiple files in one directory, and there are four arguments:
dir for defining directory
ext for defining extension
find for defining string to find
replace for defining string that replace string defined as find
Right now, this is start of the program:
dir, ext, find, replace = ARGV
dir, ext, find, replace = ARGV.shift
raise "Missing argument for directory" unless dir
raise "..." unless ext
#etc
However, when I run this program without defining arguments, it shows only first argument that is not defined (directory) with RuntimeError and imediatelly closes program. Is there any different approach for this?
I can offer you such variant:
missing_parameters = ["dir","ext","find","replace"].select{|name| eval(name).nil?}
raise "Missing parameters for #{missing_parameters.join(',')}" unless missing_parameters.empty?
But frankly speaking, i don't like the usage of eval :)

Python: Call a shell script which calls a bin. With arguments

The context: There is a map somewhere on the system with bin files which I'd like to call. They are not callable directly though, but through shell scripts which do all kinds of magic and then call the corresponding bin with: "$ENV_VAR/path/to/the/bin" "$#" (the software is non-free, that's probably why this construction is used)
The problem: Calling this from within Python. I tried to use:
from subprocess import call
call(["nameOfBin", "-input somefile"])
But this gave the error ERROR: nameOfBin - Illegal option: input somefile. This means the '-' sign in front of 'input' has disapeared along the way (putting more '-' signs in front doesn't help).
Possible solutions:
1: In some way preserving the '-' sign so the bin at the end actually takes '-input' as an option instead of 'input'.
2: Fix the magic in a dirty way (I will probably manage), and have a way to call a bin at a location defined by a $ENV_VAR (environment variable).
I searched for both methods, but appearantly nobody before me had such a problem (or I didn't see it: Sorry if that's the case).
Each item in the list should be a single argument. Replace "-input somefile" with "-input", "somefile":
from subprocess import call
rc = call(["nameOfBin", "-input", "somefile"])

Why can't I use "mkdir" with a Pathname object?

I've recently been trying out the Pathname lib, and one thing I want to do is use mkdir to create some directories.
I looked up the documentation and it says it wraps up mkdir but everytime I try to use it I`m getting this error:
irb(main):006:0> p = Pathname.new('/tmp')
=> #<Pathname:/tmp>
irb(main):007:0> a = p.mkdir("123adam")
TypeError: can't convert String into Integer
from /usr/lib/ruby/1.8/pathname.rb:975:in `mkdir'
from /usr/lib/ruby/1.8/pathname.rb:975:in `mkdir'
from (irb):7
from /usr/lib/ruby/1.8/fileutils.rb:1589
Can anyone explain what I`m doing wrong here.
You need to specify the directory you want to create with Pathname and then call mkdir.
This should work:
p = Pathname.new('/tmp/123adam')
p.mkdir
The argument you can supply are the permissions for the new directory.
Out of interest, the reason why you get "can't convert String into Integer" is because Pathname.mkdir is actually a wrapper around Dir.mkdir as follows:
def mkdir(*args) Dir.mkdir(#path, *args) end
The path represented by the Pathname object is passed as the first parameter to Dir.mkdir, followed by any parameters passed to Pathname.mkdir. The second parameter for Dir.mkdir is the numeric access permissions that you would like the directory created to have. Hence in your example "123adam" is being passed to Dir.mkdir where a number is expected.

Resources