【问题标题】:Replace ruby one liner with it do ; end block用它替换 ruby​​ 一个衬垫;结束块
【发布时间】:2016-04-29 06:29:47
【问题描述】:

我想知道如何在我的所有 rspec 文件中替换这样的代码:

describe ApiController do
  context 'article list exist' do
      #...
      it { should respond_with :success }

      it { should render_template 'refresh_article_in_article_list' }
  end
end

describe ApiController do
  context 'article list exist' do
     #...
     it do
         should respond_with :success

         should render_template 'refresh_article_in_article_list'
     end
  end
end

我可以用 vim 宏替换一个,但不能用多行替换。

this post 的帮助下,我尝试在 ruby​​ gsub 中执行此操作,但失败了,我将继续搜索:

"it { should respond_with :success }\n\nit { should render_template 'refresh_article' }".gsub(/(?<value>{.*})|(it {)|( })/, 'it do \k<value>\nend'))
=> "it do \\nend should respond_with :successit do \\nend\n\nit do \\nend should render_template 'refresh_article'it do \\nend"

【问题讨论】:

  • 你有多少这样的?也许只是手动更改它们并忘记它?
  • @sergio-tulentsev 我可能有超过 15000 条这样的一行。 :)

标签: ruby regex awk gsub


【解决方案1】:
$ cat tst.awk
NF {
    prevSpaces = spaces
    spaces = $0
    sub(/[^[:space:]].*/,"",spaces)
}
!inBlock && /it *{.*}/ {
    print spaces "it do"
    inBlock = 1
}
inBlock {
    if ( !NF ) {
        print
    }
    else if ( gsub(/.*it *{ *| *} */,"") ) {
        print spaces "    " $0
    }
    else {
        print prevSpaces "end"
        inBlock = 0
    }
}
!inBlock
$
$ awk -f tst.awk file
describe ApiController do
  context 'article list exist' do
      #...
      it do
          should respond_with :success

          should render_template 'refresh_article_in_article_list'
      end
  end
end

不确定它的作用?添加一些“打印”以查看字段和/或变量的设置,并阅读 Arnold Robbins 的《Effective Awk Programming, 4th Edition》一书,如果有任何问题,请发布具体问题。

【讨论】:

  • 感谢@ed-morton 的回答。我已经更新了问题以获取更多上下文。我试过了,没有成功。
  • 我错了。它就像一个魅力。我在一个大文件上进行了测试。下次一定会学到更多。
猜你喜欢
  • 1970-01-01
  • 2011-07-10
  • 1970-01-01
  • 2014-08-13
  • 2017-11-10
  • 2010-09-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多