在我的可执行Ruby文件中,我有以下内容:
#!/usr/bin/env ruby
require 'thor'
include Thor::Actions
class UI < Thor
# def self.source_root
# File.dirname(__FILE__)
# end
desc "makecal", "Generates postscript calendar to your desktop"
def makecal
# puts `ls ~`
puts run('ls ~')
# puts run "pcalmakecal -B -b all -d Helvetica/8 -t Helvetica/16 -S #{Time.now.month} #{Time.now.year} > ~/Desktop/#{Time.now.month}-#{Time.now.year}"
end
end
UI.start
在我运行文件的终端中,我得到一个空行,因为Thor的运行命令返回一个NilClass。
然而,当我取消评论puts`ls~`并注释掉Thor的run方法时,我得到了我的主目录的输出。
我无法弄清楚为什么我不能让Thor的run方法像Ruby一样工作。
我可能出错的任何想法?
感谢您寻找
答案 0 :(得分:1)
我没有把include语句放在我的类中,这搞砸了。代码应该是:
#!/usr/bin/env ruby
require 'makecal'
class UI < Thor
include Thor::Actions
# def self.source_root
# File.dirname(__FILE__)
# end
#
desc "makecal", "Generates postscript calendar to your desktop"
def makecal
# puts `ls ~`
puts run('ls ~')
# puts run "pcal -B -b all -d Helvetica/8 -t Helvetica/16 -S #{Time.now.month} #{Time.now.year} > ~/Desktop/#{Time.now.month}-#{Time.now.year}"
end
end
UI.start
答案 1 :(得分:1)
Thor关于这种方法的文档实际上是错误的和不完整的。它记录它返回“命令的内容”(我假设它意味着标准输出),但它通过defualt没有做任何事情。
但是,您显然可以使用:capture
选项来获得您想要的内容:
unless options[:pretend]
config[:capture] ? `#{command}` : system("#{command}")
end
所以,试试
puts run("ls ~", :capture => true)
看看是否可以。