Namespacing thor commands in a standalone ruby executable - ruby

When calling thor commands on the command line, the methods are namespaced by their module/class structure, e.g.
class App < Thor
desc 'hello', 'prints hello'
def hello
puts 'hello'
end
end
would be run with the command
thor app:hello
However, if you make that self executable by putting
App.start
at the bottom you can run the command like:
app hello
Is there any way to namespace those commands? So that you could call, for example
app say:hello
app say:goodbye

Another way of doing this is to use register:
class CLI < Thor
register(SubTask, 'sub', 'sub <command>', 'Description.')
end
class SubTask < Thor
desc "bar", "..."
def bar()
# ...
end
end
CLI.start
Now - assuming your executable is called foo - you can call:
$ foo sub bar
In the current thor version (0.15.0.rc2) there is a bug though, which causes the help texts to skip the namespace of sub commands:
$ foo sub
Tasks:
foo help [COMMAND] # Describe subcommands or one specific subcommand
foo bar #
You can fix that by overriding self.banner and explicitly setting the namespace.
class SubTask < Thor
namespace :sub
def bar ...
def self.banner(task, namespace = true, subcommand = false)
"#{basename} #{task.formatted_usage(self, true, subcommand)}"
end
end
The second parameter of formatted_usage is the only difference to the original implemtation of banner. You can also do this once and have other sub command thor classes inherit from SubTask. Now you get:
$ foo sub
Tasks:
foo sub help [COMMAND] # Describe subcommands or one specific subcommand
foo sub bar #
Hope that helps.

This is one way with App as the default namespace (quite hacky though):
#!/usr/bin/env ruby
require "rubygems"
require "thor"
class Say < Thor
# ./app say:hello
desc 'hello', 'prints hello'
def hello
puts 'hello'
end
end
class App < Thor
# ./app nothing
desc 'nothing', 'does nothing'
def nothing
puts 'doing nothing'
end
end
begin
parts = ARGV[0].split(':')
namespace = Kernel.const_get(parts[0].capitalize)
parts.shift
ARGV[0] = parts.join
namespace.start
rescue
App.start
end
Or, also not ideal:
define_method 'say:hello'

Related

Accessing the PWD inside a thor task

In my main thor file, I call this code
script.rb
# this works
current_dir = Dir.getwd
# this changes directory into the tasks
Dir.chdir(#{pwd}/tasks) {
IO.popen("thor #{ARGV * ' '}") do |io|
while (line = io.gets) do
puts line
end
io.close
end
}
tasks/example.rb
require 'thor'
class Git < Thor
include Thor::Actions
desc 'test', 'test'
def test
puts Dir.getwd # this is showing my tasks folder
end
end
Inside example.rb How can I get access to the Dir.getwd value of the script.rb and not of the example.rb (this is wrong since it is running inside the Dir.chdir).
I tried global variables and such but it doesn't seem to be working.

Thor : How can I get my Thor task to display help when I have defined an argument?

I'm converting a small project to use Thor, and being rather absent-minded I want to document the available tasks using built-in help.
But if I define a task with an argument the task-level help reverts to help for the class - which means no task description or details of the expected parameters are displayed.
I want to be be able to have a method I can call with an argument and not a parameter so it can be used like this
$ thor broke:foo hello
in a.thor broke:foo arg1=hello
I've boiled the problem down to the following thorfile which works as I want except the broken help output. I've stripped out any other parameters as they make no difference to the problem.
The first task ok:foo will display help normally, the second task broke:foo is rather less helpful :
class Ok < Thor
desc "foo", "ok test2"
def foo
puts "in a.thor ok:foo\n"
end
end
class Broke < Thor
argument :arg1, :type=>:string, :desc => "arg1"
desc "foo", "broke test1"
def foo
puts "in a.thor broke:foo arg1=#{self.arg1}\n"
end
end
Requesting help for the ok:foo task method gives :
$ thor help ok:foo
Usage:
thor ok:foo
ok test
Requesting help for the broke:foo task is rather less helpful :
$ thor help broke:foo
Tasks:
thor broke:foo ARG1 # broke test1
thor broke:help ARG1 [TASK] # Describe available tasks or one specific task
How can I define an argument and get the proper task help displayed ?
You have small mistake in your thorfile.
You have argument instead of method_option.
Here correct version:
class Ok < Thor
desc "foo", "ok test2"
def foo
puts "in a.thor ok:foo\n"
end
end
class Broke < Thor
method_option :arg1, :type=>:string, :desc => "arg1"
desc "foo", "broke test1"
def foo
puts "in a.thor broke:foo arg1=#{self.arg1}\n"
end
end
Wiki about method_option on github.com

How to use or add subcommand feature with thor?

I am creating a CLI app using thor. Its going well but now I'm stuck with the sub-command feature.
There ain't anything in its github wiki and googled around, but nothing helpful.
So, can someone show or point me out how to implement the subcommand feature?
Check out: http://whatisthor.com/
From that site (edited a bit to save space and highlight subcommand usage):
module GitCLI
class Remote ", "Adds a remote named for the repository at "
option :t, :banner => ""
option :m, :banner => ""
options :f => :boolean, :tags => :boolean, :mirror => :string
def add(name, url)
# implement git remote add
end
desc "rename ", "Rename the remote named to "
def rename(old, new)
end
end
class Git [...]", "Download objects and refs from another repository"
options :all => :boolean, :multiple => :boolean
option :append, :type => :boolean, :aliases => :a
def fetch(respository, *refspec)
# implement git fetch here
end
desc "remote SUBCOMMAND ...ARGS", "manage set of tracked repositories"
subcommand "remote", Remote ### SUBCOMMAND USED HERE...
end
end
hth...
Try something like this (file test.rb):
#!/usr/bin/env ruby
require 'rubygems'
require 'thor'
require 'thor/group' # This is required -- it's not a bug, it's a feature!
class Bar < Thor
desc "baz", "Whatever"
def baz
puts "Hello from Bar"
end
end
class Foo < Thor
desc "go", "Do something"
def go
puts "Hello there!"
end
register Bar, :bar, "bar", "Do something else"
end
if __FILE__ == $0
Foo.start
end
This behaves as follows:
> test.rb
Tasks:
test.rb bar # Do something else
test.rb go # Do something
test.rb help [TASK] # Describe available tasks or one specific task
> test.rb go
Hello there!
> test.rb bar
Tasks:
test.rb baz # Whatever
test.rb help [COMMAND] # Describe subcommands or one specific subcommand
> test.rb bar baz
Hello from Bar
> test.rb baz
Could not find task "baz".
>
(This mostly works as expected, except the help information for "test.rb bar" isn't quite right, IMHO. I think it should say "test.rb bar baz ...", instead of "test.rb baz ...".)
Hope this helps!

Writing a DSL like Thor gem in Ruby?

I'm trying to figure out how the Thor gem creates a DSL like this (first example from their README)
class App < Thor # [1]
map "-L" => :list # [2]
desc "install APP_NAME", "install one of the available apps" # [3]
method_options :force => :boolean, :alias => :string # [4]
def install(name)
user_alias = options[:alias]
if options.force?
# do something
end
# other code
end
desc "list [SEARCH]", "list all of the available apps, limited by SEARCH"
def list(search="")
# list everything
end
end
Specifically, how does it know which method to map the desc and method_options call to?
desc is pretty easy to implement, the trick is to use Module.method_added:
class DescMethods
def self.desc(m)
#last_message = m
end
def self.method_added(m)
puts "#{m} described as #{#last_message}"
end
end
any class that inherits from DescMethods will have a desc method like Thor. For each method a message will be printed with the method name and description. For example:
class Test < DescMethods
desc 'Hello world'
def test
end
end
when this class is defined the string "test described as Hello world" will be printed.

Getting module of caller in Ruby

We have code to log data in our Ruby 1.8.6 web application. You call it roughly as follows:
$log.info("Some text here")
Now, in the logged output, I would like to include the module where that line appeared. I know that the Kernel#caller will give me an array where I can pull out the file and line number that the log line occurred, but I don't want that. I want the module, not the file name. The obvious solution is to modify the log line so that it reads like:
$log.info("Some text here", self.class.name)
and then parse the result. That's not going to work, though, because I am trying to extract this information in the default case. That is, I need the solution to work if the programmer forgot to specify the module, the second parameter to the log line.
Is there any way to do this? If not, I will just have to make do with the caller array; most of our modules are in separate directories, so this would be an 80% solution.
More complete example, please excuse minor syntax errors:
in file log.rb:
module Log
class Logger
def info(msg, mod = '')
puts "Module: #{mod} Msg: #{msg}"
end
end # class Logger
end # module Log
$log = Log::Logger.new
in file foo.rb:
module Foo
class Bar
def do_something
# Do not pass in self.class.name.
# We want the output to look like:
# Module: Foo Msg: I did something!
$log.info "I did something!"
end
end # class Bar
end #module Foo
Use call_stack.
First install it with RubyGems:
gem install call_stack
Then change log.rb to:
require 'rubygems'
require 'call_stack'
call_stack_on
module Log
class Logger
def info(msg, mod = '')
mod = call_stack(2)[0][0] if mod == ''
puts "Module: #{mod} Msg: #{msg}"
end
end # class Logger
end # module Log
$log = Log::Logger.new
Works for me (Ruby 1.8.7).
$ ruby foo.rb
Module: Foo::Bar Msg: I did something!
A mixin solves the OP's specific requirements (meanwhile, +1 to Asher for solving the generic "who called me" case!).
module Log
module Logger
def info(msg)
puts "Module: #{self} Msg: #{msg}"
end
end # class Logger
end # module Log
module Foo
class Bar
include Log::Logger
def do_something
# Do not pass in self.class.name.
# We want the output to look like:
# Module: Foo Msg: I did something!
info "I did something!"
end
end # class Bar
end # module Foo
foobar = Foo::Bar.new
foobar.do_something
Came across this post while looking for an answer for my own purposes.
Didn't find one that was appropriate, so I dug through the Ruby source and put together an extension. I've bundled it as a gem- should install without any problem so long as you are using Ruby 1.9.1:
sudo gem install sender
This will not work with Ruby 1.8, as 1.8 has a different model for tracking frames.
http://rubygems.org/gems/sender

Resources