我反覆使用這個模式:注入Ruby代碼到塊中塊
pb= ProgressBar.new("blah_map", wtf.count)
newresult= cache("blah_map") do
result.map{ |r| pb.inc; { blah: r[:x] } }
end
pb.finish
或
pb= ProgressBar.new("blah_group", wtf.count)
newresult= cache("blah_group") do
result.group_by{ |r| pb.inc; "#{r[:x]}&#{r[:y]}" }
end
pb.finish
所以很自然,我想能夠做到
def progress_cache(name, count, &block)
pb= ProgressBar.new(name, count)
inject_pb_inc(block) # how??
# do some caching with yield if cache doesn't exist, don't mind this
pb.finish
end
而且使用它如此:
newresult= progress_cache("lol", result.count) do
result.map do |r|
# progress_cache magically inserted a pb.inc here for pretty animation!
r[:omg]
end
end
問題是,如何將pb.inc調用注入progress_cache塊內的塊(map,group_by等)?
編輯:改寫的問題
你需要閱讀https://github.com/bbatsov/ruby-style-guide – megas 2012-08-08 06:40:08
@megas因爲我用了四個空格嗎?當然 – nurettin 2012-08-08 06:42:02