class String
def dasherize
to_s.gsub '_', '-'
end
def switchify
length > 1 ? "--#{dasherize}" : "-#{self}"
end
end
class Hash
def switchify
inject [] do |args, (key, value)|
next args unless value
args << key.to_s.switchify
args << (value === String ? value.inspect : value.to_s) unless value === true
args
end
end
end
h = { :config => 'foo.ini', :verbose => true, :with_foo_bar => false, :with_some_coolness => true, :T => true }
p h.switchify
# => ["--config", "foo.ini", "--verbose", "--with-foo", "-T"]
p h.switchify.join(' ')
# => --config foo.ini --verbose --with-foo -T
Refactorings
No refactoring yet !
Tj Holowaychuk
April 8, 2009, April 08, 2009 21:34, permalink
dasherize should use #tr anyway twice as fast, my bad
Tj Holowaychuk
April 8, 2009, April 08, 2009 21:48, permalink
class String
def dasherize
tr '_', '-'
end
def switchify
length > 1 ? "--#{dasherize}" : "-#{self}"
end
end
class Hash
def switchify
inject [] do |args, (key, value)|
next args unless value
args << key.to_s.switchify
args << (String === value ? value.inspect : value.to_s) unless value === true
args
end
end
end
Whipped this up really quick, the output shows what I want but pretty messy IMO