简体   繁体   中英

ruby: Can't create directory with FileUtil

I have defined a module :

require 'dir'
require 'fileutils'
module Checker

  # Checks if the targetdirectory are present. If not, it creates one
  def self.check_dir
    # Checking if dir exists
    if Dir.exist?("#{@todo}")
      puts 'Found directory. Im using it.'
    else
      puts 'No directory found. Im creating it.'
      # Creates the new directory
      FileUtils.mkdir_p("#{@todo}")
        if Dir.exist?("#{@todo}")
          raise('Cant create directory')
        else
          puts 'Created new directory...'
        end
    end
  end
end

I'm using it there:

puts "Erstellt Verzeichnis #{articles_dir}/#{titel}"
@todo = "#{articles_dir}/#{titel}"
Checker.check_dir

puts 'Wechsle in article Verzeichnis'
FileUtils.cd("#{articles_dir}/#{titel}") do

[...stuff...]

end

But after running the code I'm getting:

Erstellt Verzeichnis
/home/sascha/Dokumente/Textdokumente/publican-dokumentation2/articles/TestEIns
/home/sascha/ownCloud/RubymineProjects/PublicanCreators/lib No
directory found. Im creating it.
/usr/lib/ruby/2.2.0/fileutils.rb:252:in `mkdir': No such file or
directory @ dir_s_mkdir -  (Errno::ENOENT)    from
/usr/lib/ruby/2.2.0/fileutils.rb:252:in `fu_mkdir'    from
/usr/lib/ruby/2.2.0/fileutils.rb:226:in `block (2 levels) in mkdir_p'
  from /usr/lib/ruby/2.2.0/fileutils.rb:224:in `reverse_each'     from
/usr/lib/ruby/2.2.0/fileutils.rb:224:in `block in mkdir_p'    from
/usr/lib/ruby/2.2.0/fileutils.rb:210:in `each'    from
/usr/lib/ruby/2.2.0/fileutils.rb:210:in `mkdir_p'     from
/home/sascha/RubymineProjects/PublicanCreators/lib/PublicanCreators/checker.rb:14:in
`check_dir'   from
/home/sascha/RubymineProjects/PublicanCreators/lib/PublicanCreators.rb:60:in
`<top (required)>'    from -e:1:in `load'     from -e:1:in `<main>' Process
finished with exit code 1

As varibles i'm using:

home = Dir.home
publican_doc_dir = "#{home}/Dokumente/Textdokumente/publican-dokumentation2"
articles_dir = "#{publican_doc_dir}/articles"
titel = `yad --entry --button="Bestätigen" --title="Neuen Artikel erstellen" --text="Gebe ein Titel ein (Mit Unterstrichen statt Leerzeichen und ohne Umlaute):"`

A puts titel gives me the correct output.

Maybe I missed anything?

This is because instance variable @todo is not defined/available inside your module Checker .

You can validate this using:

module Checker
 def self.check_dir
  puts @todo
 end
end

@todo = "hello"
Checker::check_dir
#
# => nil

Refer to this SO for details on how instance variables are available inside modules.

Another thing i found is that mkdir creates #{publican_doc_dir}/articles/#{title}?/#{title}. So articles/test01?/test01 instead of articles/test01. Strange thing...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM