1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
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