2

Ruby でファイル IO を学び始めたばかりで、::expand_path を使用して、プログラムが実行されている場所とは別のパスに移動できるかどうかについて質問がありました。

これが私が本質的にできるようにしたいことですが、残念ながらこれは私にとってはうまくいきません。

require 'openuri'
require 'fileutils'

if File.expand_path.exists?("~/newpathdir/")
        File.expand_path.open("~/newpathdir/log.txt", "a+") {|f| f.write("#{Time.now}       Directory is good.  Returning...") }        #If directory is present, does nothing
        return
    else
        FileUtils.mkdir_p.expand_path("~/newpathdir/")
        File.open("~/newpathdir/log.txt", "a+") {|f| f.write("#{Time.now}       Directory not found.  Creating...") }       #If directory not found, writes to log
    end

def writeLatestToFile
    tweet_file = File.open("~/newpathdir/latest_tweet.txt", "a+")       #Opens file
        if tweet_file       #Checks if file opened correctly
            tweet_file.syswrite("#{@latest_tweet["ID"]}\n#{@latest_tweet["Tweet"]}")        #Appends latest_command information to latest_command.txt
        elsif
            File.open("~/newpathdir/log.txt", 'a+') {|f| f.write("#{Time.now}       Error opening tweet_file.txt") }        #If error in opening file, writes to log
        end
end

どんな助けでも大歓迎です。

4

1 に答える 1

1

これは、あなたの望むことですか?

require 'fileutils'

def append(path, message)
  path = File.expand_path path
  FileUtils.mkdir_p File.dirname(path)
  File.open(path, "a+") {|f| f.write "#{message}\n" }
end

def log(path, message)
  append(path, "#{Time.now} #{message}")
end

append('~/newpathdir/latest_tweet', "123456\nLatestTweet")
log('~/newpathdir/log', 'Hello world')

多分あなたも試してみるべきLoggerです。クラス: ロガー (Ruby 1.9.3)

require 'logger'
require 'fileutils'

path = File.expand_path '~/newnewpathdir/tweets_logger.log'
FileUtils.mkdir_p File.dirname(path)
log = Logger.new(path)

log.debug('Hello world.')
log.info('Info message.')
log.error('Error message.')
于 2013-05-11T05:55:00.260 に答える