Class: Binder::Strategy

Inherits:
Object
  • Object
show all
Defined in:
lib/cli/command.rb

Overview

Public: A Strategy is a way to declare a specific command. You need to subclass the Binder::Strategy class and declare an ‘execute` method and a `description` method.

Examples

class Migrate < Binder::Strategy
  def execute args
    # Parse args and do migration stuff
    "Migration Done." # <= Binder::Command.new automaticaly renders the return value of an `execute` call
  end
  #
  # The description call is mainly used by the `help` command.
  def description
    "Easier Migration. Use the " + "--directory".colorize(:orange) + " option to pass in a directory to load."
    # Yeah, notice the "colorize" String method that helps you write a string in a beatiful color.
  end
end

Direct Known Subclasses

Help, Migrate, Version

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.alias_class(_alias) ⇒ Object

Public: creates an alias for the command.

Examples

class Migrate < Binder::Strategy
  # def execute...
  # def description...
  #
  alias_class :M
  # => This will create an alias :M class and this the existance of the corresponding "-m" command. (`arb --migrate` or `arb -m`, now)
end


57
58
59
# File 'lib/cli/command.rb', line 57

def self.alias_class _alias
  Binder::const_set(_alias, Class.new(self))
end

Instance Method Details

#descriptionObject

Public: provides a default description if not defined.

Returns a “No description found” String.



99
# File 'lib/cli/command.rb', line 99

def description; "No description found" end

#justify_sizeObject

Public: returns the String size of the biggest command or option group.

Returns a Numeric.



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

def justify_size
  if @options.nil?
    Binder::Strategy.subclasses.map(&:to_s).group_by(&:size).max.flatten.first - "Binder".length
  else
    @options.group_by(&:size).max.flatten.first
  end
end

#merge_options_aliasesObject

Public: merge options and aliases “-m, –migrate, -h, –help”, etc…

Uses an array of commands : [“-h” “-m”, “–help”, “–migrate”],

and concatenate the aliases : [“-m, –migrate”, “-h, –help”]

Returns an Array of merged aliases.



79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/cli/command.rb', line 79

def merge_options_aliases
  commands     = Binder::Strategy.subclasses.map { |command| command.to_s.gsub!('Binder::', '').downcase }.sort
  previous_cmd = ""
  options      = []

  commands.each_with_index do |cmd, i|
    if cmd.length == 1
      previous_cmd = cmd
    elsif not previous_cmd.empty?
      cmd_prefixes = [previous_cmd.length == 1 ? '-' : '--', cmd.length == 1 ? '-' : '--']
      options << "#{cmd_prefixes.first}#{previous_cmd}, #{cmd_prefixes.last}#{cmd}"
      previous_cmd = ""
    end
  end
  @options = options
end