F1e3ab214a976a39cfd713bc93deb10f

Whipped this up really quick, the output shows what I want but pretty messy IMO

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 !

F1e3ab214a976a39cfd713bc93deb10f

Tj Holowaychuk

April 8, 2009, April 08, 2009 21:28, permalink

No rating. Login to rate!

Whoops, ignore to_s for #dasherize

F1e3ab214a976a39cfd713bc93deb10f

Tj Holowaychuk

April 8, 2009, April 08, 2009 21:34, permalink

No rating. Login to rate!

dasherize should use #tr anyway twice as fast, my bad

F1e3ab214a976a39cfd713bc93deb10f

Tj Holowaychuk

April 8, 2009, April 08, 2009 21:48, permalink

No rating. Login to rate!
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

Your refactoring





Format Copy from initial code

or Cancel