如何在Ruby中使用大括号扩展?

时间:2013-01-07 15:46:21

标签: ruby

假设我想要以下规格:

it { should allow_value("git://host.xz/path/to/repo.git/").for(:url) }
it { should allow_value("git://user@host.xz/path/to/repo.git/").for(:url) }
it { should allow_value("git://host.xz:123/path/to/repo.git/").for(:url) }
it { should allow_value("git://user@host.xz:123/path/to/repo.git/").for(:url) }
...

如果我能写的话会更简单,更紧凑:

"git://{user@,}host.xz{:123,}/path/to/repo.git".expand.each do |p|
  it { should allow_value(p).for(:url) }
end

甚至更好:

"{git,ssh,http,https,rsync}://[user@]host.xz[:123]/path/to/repo.git[/]".expand.each do |p|
  it { should allow_value(p).for(:url) }
end

有哪些方法可以在Ruby中实现这一目标?

修改 我尝试的第一件事是bracecomp,但我无法在1.9.3中使用它。

[1] pry(main)> require 'bracecomp'
[2] pry(main)> 'server-{a,b}-{07..10}'.expand
TypeError: scan() yielded Symbol (must be Array[2])
from bracecomp.y:66:in `scan'

2 个答案:

答案 0 :(得分:4)

怎么样

%w[git ssh http https rsync].product(['user@', nil], [':123', nil]).each do |protocol, user, port|
  it { should allow_value("#{protocol}://#{user}host.xz#{port}/path/to/repo.git").for(:url) }
end

不依赖于外部库,并且每个Ruby开发人员都能理解。

虽然这确实对规范助手或自定义匹配器感到尖叫,但我认为。

答案 1 :(得分:1)

bracecomp-0.1.2可用于执行大括号扩展。以下是宝石主页的一个例子:

require 'bracecomp'
p 'server-{a,b}-{07..10}'.expand
#=> ["server-a-07", "server-a-08", "server-a-09", "server-a-10", "server-b-07", "server-b-08", "server-b-09", "server-b-10"]
p 'zone-{a..c}'.expand
#=> ["zone-a", "zone-b", "zone-c"]