如何转换Ruby块并将其作为参数应用于另一个块?

时间:2014-05-12 09:22:17

标签: ruby

我用我写的一个小捷径方法减少了许多相关规范的详细程度:

def association_spec_for(kind, field)
  it { expect(subject).to send(kind, field) }
end

这样使用:

describe Student do
  association_spec_for :have_many, :courses
  association_spec_for :have_one, :transcript
end

现在我想扩展association_spec_for的工作方式,这样我就可以做到这一点,同时保持原始用例的完整性:

association_spec_for(:foo, :bar) do |a|
  a.baz(:blerp).bloop(:bleep => :blarg)
end

并将其变为:

it { expect(subject).to send(:foo, :bar).baz(:blerp).bloop(:bleep => :blarg) }

                                      # |----------------------------------|
                                      #    This part came from the block
                                      #      that was passed to a_s_f.

实现这一目标的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

def association_spec_for(kind, field, &pr)
  it{expect(subject).to pr ? pr.call(send(kind, field)) : send(kind, field)}
end