Thor Executable - Ignore Task Name
Asked Answered
S

3

12

The thor wiki page, Making an Exectable, shows you how to create a thor powered CLI command that looks something like this:

bash ./mythorcommand foo

This requires you to pass in the thor task foo as the first argument.

I can also run a thor executable without any arguments using thor's default_method:

bash ./mythorcommand

However, I'd like to pass in a variable string as the first argument:

bash ./mythorcommand "somevalue"

This doesn't work because thor commands expect the first argument to the be a task name. Is there a way to ignore the task name and send the first argument to a default method?

If this functionality doesn't exist, I think it would be very useful to add a method that would pass all commandline arguments into one task/method:

class MyThorCommand < Thor
  only_method :default

  def default(*args)
    puts args.inpsect
  end 
end 

MyThorCommand.start
Stale answered 1/9, 2011 at 23:5 Comment(0)
D
4

You should extend from Thor::Group and that call start method

class Test < Thor::Group
  desc "Act description"
  def act
    puts "do smth"
  end
end

Test.start
Disappoint answered 2/12, 2011 at 20:34 Comment(2)
This answer is correct. Use argument :bar to make the contents of the unnamed string argument available by calling bar inside #act. Thor will find this argument whether it's before or after any options defined by class_options.Olvera
Beware that Thor::Group calls all tasks at once.Naidanaiditch
I
3

I found a rather 'strange' solution for this problem that is working quite well with me.

You add a default task to Thor. Than you add the method_missing so that you can trick Thor into passing the default method as an argument if there are parameters to your application.

Taking from your example, the solution would look like this:

class MyThorCommand < Thor
  default_task :my_default

  desc "my_default", "A simple default"
  def my_default(*args)
    puts args.inspect
  end 

  def method_missing(method, *args)
    args = ["my_default", method.to_s] + args
    MyThorCommand.start(args)
  end

end 

MyThorCommand.start(ARGV)

If this is in the file "my_thor.rb" an execution "ruby my_thor.rb foo bar" would show '["foo", "bar"]' as a result.

Hope it helps.

Inanition answered 30/5, 2014 at 13:38 Comment(0)
W
1

Though this does not exactly solve your problem, one alternative might be using Thor.map to invoke a command by only giving an option flag:

map '-F' => 'foo'

Now you can also pass parameters

mythorcommand -F bar # => invokes foo("bar")
Wilsonwilt answered 5/9, 2011 at 17:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.