Sha256: f6f1ed59ac2ac43b0eda443ccc36eacc5c5fd1ae94366d794dd8abae0770dcfd

Contents?: true

Size: 1.33 KB

Versions: 5

Compression:

Stored size: 1.33 KB

Contents

module Clamp

  class Option

    def initialize(switches, type, description, options = {})
      @switches = Array(switches)
      @type = type
      @description = description
      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 :switches, :type, :description, :default_value

    def attribute_name
      @attribute_name ||= long_switch.sub(/^--(\[no-\])?/, '').tr('-', '_')
    end
    
    def long_switch
      switches.find { |switch| switch =~ /^--/ }
    end

    def handles?(switch)
      recognised_switches.member?(switch)
    end

    def flag?
      @type == :flag
    end
    
    def flag_value(switch)
      !(switch =~ /^--no-(.*)/ && switches.member?("--\[no-\]#{$1}"))
    end
    
    def extract_value(switch, arguments)
      if flag?
        flag_value(switch)
      else
        arguments.shift
      end
    end
    
    def help
      lhs = switches.join(", ")
      lhs += " " + type unless flag?
      [lhs, description]
    end

    private

    def recognised_switches
      switches.map do |switch|
        if switch =~ /^--\[no-\](.*)/
          ["--#{$1}", "--no-#{$1}"]
        else
          switch
        end
      end.flatten
    end
    
  end

end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
clamp-0.1.3 lib/clamp/option.rb
clamp-0.1.2 lib/clamp/option.rb
clamp-0.1.1 lib/clamp/option.rb
clamp-0.1.0 lib/clamp/option.rb
clamp-0.0.9 lib/clamp/option.rb