jklina
jklina

Reputation: 3417

Running command line commands from Thor executable

In my executable Ruby file I have the following:

#!/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

In the terminal when I run the file as is I get an empty line as Thor's run command is returning a NilClass.

However, when I un-comment the puts `ls ~` and comment out Thor's run method I get an output of my home directory as expected.

I'm having trouble figuring out why I can't get Thor's run method to work like Ruby's ticks.

Any ideas where I may have went wrong?

Thanks for looking

Upvotes: 1

Views: 1837

Answers (2)

davetron5000
davetron5000

Reputation: 24841

Thor's documentation on this method is actually wrong and incomplete. It documents that it returns the "contents of the command" (which I assume means the standard output), but it, by defualt, does nothing.

But, you can, apparently, use the :capture option to get what you want:

unless options[:pretend]
  config[:capture] ? `#{command}` : system("#{command}")
end

So, try doing

puts run("ls ~", :capture => true)

And see if that does it.

Upvotes: 1

jklina
jklina

Reputation: 3417

I didn't put the include statement inside my class and that messed things up. The code should be:

#!/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

Upvotes: 1

Related Questions