簡體   English   中英

如何轉換Ruby塊並將其作為參數應用到另一個塊?

[英]How do I transform a Ruby block and apply it as an argument to another block?

我通過編寫的一種快捷方式來減少許多相關規范的冗長性:

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.

做到這一點的最佳方法是什么?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM