Skip to content
Ryan S. Northrup edited this page Aug 10, 2015 · 1 revision
#!/usr/bin/env ruby

# If you've read the overview already, you'd know full well by now
# that we can define subcommands up to at least one level:

class MyApp::Application < Bales::Application
  version "1.2.3"
  summary "Some random app"
  description "Some longer description of this random app"

  action do
    puts "I'm the root command!"
  end

  command "foo" do
    action do
      puts "I'm a subcommand of Bales::Command!"
    end
  end

  parse_and_run
end

# But what if we want to go even deeper?  A command within a command?
# Well, turns out that's dead simple, too.

class MyApp::Application
  command "foo bar" do
    action do
      puts "I'm a subcommand of Bales::Command::Foo!"
    end
  end
end

# Whaa?  Well, this is really just a pinch of fairy dust to create a
# namespace hierarchy that looks more-or-less like the following (with
# a lot of simplification to ignore some behind-the-scenes stuff
# that's generated):

class MyApp::Command < Bales::Command
  class Foo
    class Bar
      def run
        puts "I'm a subcommand of Bales::Command::Foo!"
      end
    end

    def run
      puts "I'm a subcommand of Bales::Command!"
    end
  end

  def run
    puts "I'm the root command!"
  end
end

# This namespace hierarchy is then matched up to the arguments that
# MyApp receives when it's run (namely, by the `parse_and_run` method
# invoked in MyApp::Application's definition) and automatically
# dispatched upon.  Pretty sweet, eh?

# And of course, we can go as deep as we want (subject to the
# limitations of one's shell and of Ruby itself, of course; Your
# Mileage May Vary(TM)):

class MyApp::Application
  command "foo bar baz bam bat baf far faz fat faf yada yada yada" do
    action do
      puts "I'm MyApp::Command::Foo::Bar::Baz::Bam::Bat::Baf::Far::Faz::" \
           "Fat::Faf::Yada::Yada::Yada!"
    end
  end

  command "bork bork bork" do
    action do
      puts "Hellu, vurld!  Bork Bork Bork!"
    end
  end
end

# Now go forth and create some subcommands!
Clone this wiki locally