Module: Dry::CLI::Inline

Extended by:
Forwardable
Defined in:
lib/dry/cli/inline.rb

Overview

Inline Syntax (aka DSL) to implement one-file applications

‘dry/cli/inline` is not required by default and explicit requirement of this file means that it is expected of abusing global namespace with methods below

DSL consists of 5 methods: ‘desc`, `example`, `argument`, `option`  — are similar to methods from Command class

‘run` accepts a block to execute

Examples:

require 'bundler/inline'
gemfile { gem 'dry/cli', require: 'dry/cli/inline' }

desc 'List files in a directory'
argument :path, required: false, desc: '[DIR]'
option :all, aliases: ['a'], type: :boolean

run do |path: '.', **options|
  puts options.key?(:all) ? Dir.entries(path) : Dir.children(path)
end

# $ ls -a
# $ ls somepath
# $ ls somepath --all

Since:

  • 0.6.0

Constant Summary collapse

AnonymousCommand =

AnonymousCommand

Since:

  • 0.6.0

Class.new(Dry::CLI::Command)

Instance Method Summary collapse

Instance Method Details

#run(arguments: ARGV, out: $stdout) ⇒ Object

The rule of thumb for implementation of run block is that for every argument from your CLI you need to specify that as an mandatory argument for a block. Optional arguments have to have default value as ruby syntax expect them

Examples:

argument :one
argument :two, required: false
option :three

run do |one:, two: 'default', **options|
  puts one, two, options.inspect
end

Since:

  • 0.6.0



63
64
65
66
67
68
69
70
# File 'lib/dry/cli/inline.rb', line 63

def run(arguments: ARGV, out: $stdout)
  command = AnonymousCommand
  command.define_method(:call) do |**args|
    yield(**args)
  end

  Dry.CLI(command).call(arguments: arguments, out: out)
end