Sha256: 9c9af776b4dc78835424156fd03739b72cbc3b7d25cb14f3dc5dc713dda1e1c1

Contents?: true

Size: 1002 Bytes

Versions: 1

Compression:

Stored size: 1002 Bytes

Contents

require 'slop'

module Lita
  module Extensions
    class KeywordArguments
      class Parser
        attr_reader :args, :spec

        def initialize(spec, args)
          @spec = spec
          @args = prepare_args(args)
        end

        def parse
          spec.each { |name, option_spec| add_option(name, option_spec) }
          parser.parse(args)
          parser.to_hash
        end

        private

        def add_option(name, spec)
          opt_args = []
          opt_options = {}

          opt_args << spec[:short] if spec[:short]
          opt_args << name
          opt_options[:default] = spec[:default] if spec[:default]
          opt_options[:optional_argument] = true unless spec[:boolean]
          opt_args << opt_options

          parser.on(*opt_args)
        end

        def prepare_args(args)
          args.map do |arg|
            arg.tr('—', '--')
          end
        end

        def parser
          @parser ||= Slop.new
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
lita-keyword-arguments-1.0.1 lib/lita/extensions/keyword_arguments/parser.rb