Sha256: 8309d70c917ca045531fc952573585a961ed6c81e38dc520fc0d32ff04bf1437

Contents?: true

Size: 1.48 KB

Versions: 8

Compression:

Stored size: 1.48 KB

Contents

require 'clamp/attribute'

module Clamp

  class Parameter < Attribute

    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
      if options.has_key?(:default)
        @default_value = options[:default]
      end
    end

    attr_reader :name, :attribute_name
    
    def help_lhs
      name
    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

    NAME_PATTERN = "([A-Za-z0-9_-]+)"
    
    def infer_attribute_name_and_multiplicity
      case @name
      when /^\[#{NAME_PATTERN}\]$/
        @attribute_name = $1
      when /^\[#{NAME_PATTERN}\] ...$/
        @attribute_name = "#{$1}_list"
        @multivalued = true
      when /^#{NAME_PATTERN} ...$/
        @attribute_name = "#{$1}_list"
        @multivalued = true
        @required = true
      when /^#{NAME_PATTERN}$/
        @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

8 entries across 8 versions & 2 rubygems

Version Path
clamp-0.3.0 lib/clamp/parameter.rb
clamp-0.2.3 lib/clamp/parameter.rb
clamp-0.2.2 lib/clamp/parameter.rb
clamp-0.2.1 lib/clamp/parameter.rb
clamp-0.2.0 lib/clamp/parameter.rb
wpb-0.0.5 lib/wpb/clamp/parameter.rb
clamp-0.1.8 lib/clamp/parameter.rb
clamp-0.1.7 lib/clamp/parameter.rb