By Navroop


2019-05-15 16:31:43 8 Comments

I have a folder with multiple pdf files and the file name are like this as below

1_abc.pdf
2_xyz.pdf
3_qwe.pdf

What is want to do is just get the first part of the file name that is

1
2
3

So I am trying to generate a rake task to get that working but I am not about to figure-out how to implement it on a multiple files.

namespace :request_document do
  desc "Expects to get a file or folder ..."
  task(:import_attachment, [:filename]) do |t, args|
    files = Dir.foreach("/Users/admin/Documents/Data/Attachments")
     puts files
      *This gives the list of all the files under the attachment folder*
  end
end

So I was thinking of using something like this

File.basename"1_abc.pdf".sub(/\_..*/, '')
=>  1

and this give the out as 1 which is what I need but I am not able to figure that out how to implement it on multiple files. Like it loops over all the files in the attachments folder and get me the first part of the filename. Please help me figure-out.

1 comments

@kriskova 2019-05-15 16:47:08

You can simply iterate over the filenames like:

Dir["/Users/admin/Documents/Data/Attachments/*"].each do |filename|
  puts File.basename(filename).sub(/\_.*/, '')
end

So with that the rake task would look something like this:

namespace :request_document do
  desc "Expects to get a file or folder ..."
  task(:import_attachment, [:path]) do |t, args|
    if File.directory?(args[:path])
      Dir["#{path}/*"].each do |file_path|
        puts File.basename(file_path).sub(/\_.*/, '')
      end
    else
      puts File.basename(args[:path]).sub(/\_.*/, '')
    end
  end
end

Related Questions

Sponsored Content

4 Answered Questions

[SOLVED] Difference between rake db:migrate db:reset and db:schema:load

1 Answered Questions

[SOLVED] How can I get around-hook-like behavior for rake tasks?

2 Answered Questions

[SOLVED] Rake Task w/ ActionMailer - Undefined Method Error

1 Answered Questions

[SOLVED] Rake task outside of namespace

6 Answered Questions

[SOLVED] Why is rake db:migrate:reset not listed in rake -T?

1 Answered Questions

Bulk Upload of files using paperclip

1 Answered Questions

3 Answered Questions

[SOLVED] Rake task not adding CSV to database

1 Answered Questions

[SOLVED] Rails engine models in Rake task

3 Answered Questions

Sponsored Content