Sha256: 756fa4d0c9603388be0d83051badacc171aeb6119837fbafaefb785577c1c107

Contents?: true

Size: 1.56 KB

Versions: 2

Compression:

Stored size: 1.56 KB

Contents

module Spinebox
  module Command
    
    @@commands = []
    
    # Registers a command to dispatch
    def self.on command, desc, options = {}
      @@commands << Command.new(command, desc, options, &Proc.new)
    end
    
    # Executes the matching commands
    def self.execute
      @@commands.each { |command| command.run! }
    end
    
    # Dispatches the command registering block and executes the matching commands
    def self.dispatch
      raise "Nothing to dispatch" unless block_given?
      self.module_exec(&Proc.new)
      execute
    end
    
    # The registered commands
    def self.commands
      @@commands
    end
    
    # Combines the information of all registered commands and concatenates them to a string
    def self.help
      puts "Usage:"
      printf "%-3s %s\n\n", "", "spinebox new APP_PATH"
      
      puts "Options:"
      @@commands.each { |command| printf "%-3s %-20s %s\n", "", command.command, command.desc if command.options[:type] == :option }
      
      puts ""
      
      puts "Actions:"
      @@commands.each { |command| printf "%-3s %-20s %s\n", "", command.command, command.desc if command.options[:type] == :action }
    end
    
    # Encapsules a registered command
    class Command
      
      attr_reader :command
      attr_reader :desc
      attr_reader :options
      
      def initialize command, desc, options, &block
        @command, @desc, @options, @block = command, desc, options, block
      end
      
      def run!
        return false unless @options[:if].call
        @block.call
      end
      
    end
    
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
spinebox-0.0.5 lib/spinebox/command.rb
spinebox-0.0.4 lib/spinebox/command.rb