Sha256: 4ed3574f75398935d9a0ff27269efc3d9f001539c2352d3dbb34ef81e16e616c

Contents?: true

Size: 1.29 KB

Versions: 1

Compression:

Stored size: 1.29 KB

Contents

module Clamp

  class Parameter

    def initialize(name, description, options = {})
      @name = name
      @description = description
      infer_attribute_name_and_multiplicity
      if options.has_key?(:attribute_name)
        @attribute_name = options[:attribute_name].to_s 
      end
    end

    attr_reader :name, :description, :attribute_name
    
    def help
      [name, description]
    end

    def consume(arguments)
      if required? && arguments.empty?
        raise ArgumentError, "no value provided"
      end
      if multivalued?
        arguments.shift(arguments.length)
      else
        arguments.shift
      end
    end
    
    private

    def infer_attribute_name_and_multiplicity
      case @name
      when /^\[(\S+)\]$/
        @attribute_name = $1
      when /^\[(\S+)\] ...$/
        @attribute_name = "#{$1}_list"
        @multivalued = true
      when /^(\S+) ...$/
        @attribute_name = "#{$1}_list"
        @multivalued = true
        @required = true
      when /^\S+$/
        @attribute_name = @name
        @required = true
      else
        raise "invalid parameter name: '#{name}'"
      end
      @attribute_name = @attribute_name.downcase.tr('-', '_')
    end
    
    def multivalued?
      @multivalued
    end

    def required?
      @required
    end
    
  end

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
clamp-0.0.9 lib/clamp/parameter.rb