Check if a filename is a folder or a file - ruby

I have a little piece of Ruby code:
files.each do |file|
FileUtils.mkdir_p(File.dirname(target))
FileUtils.cp_r(file, target, :verbose => true)
end
I would like to add a check like
if file is a folder
# do this
if file is a file
# do that
How do I implement in Ruby?

You can use File.directory?("name") and/or File.file?("name").

Also a good idea to check out Pathname#directory? and Pathname#file?

Related

How to change a file's path within ruby

I'm trying to move files from one folder to another via Ruby, but I'm stuck trying to get Pathname.new to work. For reference the files are being held in array as an inbetween from their normal dir. I know I could move it via CLI but I'd like the program to do it for me. This is what I have so far. I know it's wrong; I just don't get how to fix it.
temp_array.each {|song| song.path(Pathname.new("/Users/tsiege/Desktop/#{playlist_name}"))}
Have a look at FileUtils.mv:
require 'fileutils'
temp_array.each do |song|
FileUtils.mv song.path, "/Users/tsiege/Desktop/#{playlist_name}"
end
Be sure that the directory #{playlist_name} exists before you do, though:
FileUtils.mkdir_p "/Users/tsiege/Desktop/#{playlist_name}"
To move files you can use FileUtils.mv:
require 'fileutils'
FileUtils.mv 'from.ext', 'to.ext'
http://ruby-doc.org/stdlib-1.9.3/libdoc/fileutils/rdoc/FileUtils.html#method-c-mv
And if you want a list of files in a directory you can use:
Dir['/path/to/dir/*']
http://ruby-doc.org/core-1.9.3/Dir.html
Lastly, you may also want to check if you have a file or directory:
File.file? file
File.directory? dir
http://ruby-doc.org/core-1.9.3/File.html#method-c-file-3F

Test all subclasses on file update

I am learning unit testing with PHP and am following the TDD session on tutsplus: http://net.tutsplus.com/sessions/test-driven-php/
I have set up a ruby watchr script to run the PHPUnit unit tests every time a file is modified using Susan Buck's script: https://gist.github.com/susanBuck/4335092
I would like to change the ruby script so that in addition to testing a file when it is updated it will test all files that inherit from it. I name my files to indicate inheritance (and to group files) as Parent.php, Parent.Child.php, and Parent.Child.GrandChild.php, etc so the watchr script could just search by name. I just have no idea how to do that.
I would like to change:
watch("Classes/(.*).php") do |match|
run_test %{Tests/#{match[1]}_test.php}
end
to something like:
watch("Classes/(.*).php") do |match|
files = get all classes that inherit from {match[1]} /\b{match[1]}\.(.*)\.php/i
files.each do |file|
run_test %{Tests/{file}_test.php}
end
end
How do I do the search for file names in the directory? Or, is there an easier/better way to accomplish this?
Thanks
EDIT
This is what I ended up with:
watch("#{Library}/(.*/)?(.*).php") do |match|
file_moded(match[1], match[2])
end
def file_moded(path, file)
subclasses = Dir["#{Library}/#{path}#{file}*.php"]
p subclasses
subclasses.each do |file|
test_file = Tests + file.tap{|s| s.slice!(".php")}.tap{|s| s.slice!("#{Library}")} + TestFileEnd
run_test test_file
end
end
Where Library, Tests, and TestFileEnd are values defined at the top of the file. It was also changed so that it will detect changes in subfolders to the application library and load the appropriate test file.
I'm not entirely certain, but i think this will work:
watch("Classes/(.*).php") do |match|
subclasses = Dir["Classes/#{match[1]}*.php"]
filenames = subclasses.map do |file|
file.match(/Classes\/(.*)\.php/)[1]
end
filenames.each do |file|
run_test "Tests/#{file}_test.php"
end
end
It's probably not the cleaneast way, but it should work.
The first line saves all the relative paths to files in the Classes directory beginning with the changed filename in subclasses.
in the map block I use a regex to only get the filename, without any folder names or the .php extensions.
Hope this helps you

ruby-inotify example?

I'm looking for a simple, concise example of using the inotify gem to detect a change to a directory.
It lacks examples.
There's an example in examples/watcher.rb.
That link is to aredridel's repo, since it looks like you linked to aredridel's docs, and aredridel is the one who wrote the example.
One of my projects I have used ruby-inotify for monitoring file creation under specific folder using following code
# frozen_string_literal: true
require 'rb-inotify'
# observe indicate folder, trigger event after
module ObserveFiles
def self.observe
watcher = INotify::Notifier.new
directory = CONFIG['xml_folder'] # folder that want to watch
watcher.watch(directory, :create) do |event|
# do your work where
# here, event.name is created file name
# event.absolute_name file absolute path
end
watcher.run
end
end
Use this code like
ObserveFiles.observe
Hope this will help someone.

how to choose file with certain extension? ruby

I want ruby to look for a file in the current folder that ends with a certain extension. The extension would be .app.zip
How would I do this?
To get the first matching file in the current directory, you can use:
file=Dir['*.app.zip'].first
Or to find all .app.zip files in certain directory, for example files/*.app.zip, you can use something like :
Dir[File.join('files', '*.app.zip')].each |file|
puts "found: #{file}"
end
Alternative to Dir:
require "find"
Find.find(folder) do |file|
puts "#{file}" if file=~/\.app\.zip/
end

Best way to require all files from a directory in ruby?

What's the best way to require all files from a directory in ruby ?
How about:
Dir["/path/to/directory/*.rb"].each {|file| require file }
If it's a directory relative to the file that does the requiring (e.g. you want to load all files in the lib directory):
Dir[File.dirname(__FILE__) + '/lib/*.rb'].each {|file| require file }
Edit: Based on comments below, an updated version:
Dir[File.join(__dir__, 'lib', '*.rb')].each { |file| require file }
Try the require_all gem:
http://github.com/jarmo/require_all
https://rubygems.org/gems/require_all
It lets you simply:
require_all 'path/to/directory'
Dir[File.dirname(__FILE__) + '/../lib/*.rb'].each do |file|
require File.basename(file, File.extname(file))
end
If you don't strip the extension then you may end up requiring the same file twice (ruby won't realize that "foo" and "foo.rb" are the same file). Requiring the same file twice can lead to spurious warnings (e.g. "warning: already initialized constant").
Dir.glob(File.join('path', '**', '*.rb'), &method(:require))
or alternatively, if you want to scope the files to load to specific folders:
Dir.glob(File.join('path', '{folder1,folder2}', '**', '*.rb'), &method(:require))
explanation:
Dir.glob takes a block as argument.
method(:require) will return the require method.
&method(:require) will convert the method to a bloc.
The best way is to add the directory to the load path and then require the basename of each file. This is because you want to avoid accidentally requiring the same file twice -- often not the intended behavior. Whether a file will be loaded or not is dependent on whether require has seen the path passed to it before. For example, this simple irb session shows that you can mistakenly require and load the same file twice.
$ irb
irb(main):001:0> require 'test'
=> true
irb(main):002:0> require './test'
=> true
irb(main):003:0> require './test.rb'
=> false
irb(main):004:0> require 'test'
=> false
Note that the first two lines return true meaning the same file was loaded both times. When paths are used, even if the paths point to the same location, require doesn't know that the file was already required.
Here instead, we add a directory to the load path and then require the basename of each *.rb file within.
dir = "/path/to/directory"
$LOAD_PATH.unshift(dir)
Dir[File.join(dir, "*.rb")].each {|file| require File.basename(file) }
If you don't care about the file being required more than once, or your intention is just to load the contents of the file, perhaps load should be used instead of require. Use load in this case, because it better expresses what you're trying to accomplish. For example:
Dir["/path/to/directory/*.rb"].each {|file| load file }
Instead of concatenating paths like in some answers, I use File.expand_path:
Dir[File.expand_path('importers/*.rb', File.dirname(__FILE__))].each do |file|
require file
end
Update:
Instead of using File.dirname you could do the following:
Dir[File.expand_path('../importers/*.rb', __FILE__)].each do |file|
require file
end
Where .. strips the filename of __FILE__.
Dir[File.join(__dir__, "/app/**/*.rb")].each do |file|
require file
end
This will work recursively on your local machine and a remote (Like Heroku) which does not use relative paths.
In Rails, you can do:
Dir[Rails.root.join('lib', 'ext', '*.rb')].each { |file| require file }
Update: Corrected with suggestion of #Jiggneshh Gohel to remove slashes.
I'm a few years late to the party, but I kind of like this one-line solution I used to get rails to include everything in app/workers/concerns:
Dir[ Rails.root.join *%w(app workers concerns *) ].each{ |f| require f }
And what about: require_relative *Dir['relative path']?

Resources