module Autoconf extend self def switches(config=nil) case config when String switch(config) when Enumerable config.map {|item| switch(item) }.join(" ").strip else "" end end private def switch(*items) items = items.flatten case items.size when 1 plain_switch(items.first) when 2 value_switch(items.first, items.last) else "" end end def plain_switch(sw) if sw.respond_to?(:to_s) if sw.to_s =~ /^\s*(-|$)/ sw else "--#{sw}" end else "" end end def value_switch(key, value) if value && key.respond_to?(:to_s) && value.respond_to?(:to_s) value == true ? plain_switch(key) : "--#{key}=#{value}" else "" end end end if $0 == __FILE__ require 'rubygems' require 'spec/autorun' describe "Autoconf" do describe "switches" do it "should return an empty string by default" do Autoconf.switches.should == "" end it "should process an empty string untouched" do Autoconf.switches("").should == "" end it "should process a string without embedded switches as prefixed with --" do Autoconf.switches("debug").should == "--debug" end it "should process a string with embedded switches untouched" do Autoconf.switches("--debug").should == "--debug" end it "should process a hash as switches joined with =" do Autoconf.switches(:prefix => "/usr/local").should == "--prefix=/usr/local" end it "should process a hash with true values as singleton switches" do Autoconf.switches('with-ssl' => true, 'with-ssl-proxy' => true).should == "--with-ssl --with-ssl-proxy" end it "should process a hash with nil or false values ignoring those switches" do Autoconf.switches('debug' => false, 'with-poll' => nil).should == "" end it "should process an array with nil values ignoring them" do Autoconf.switches([nil]).should == "" Autoconf.switches(["debug", nil]).should == "--debug" end end end end