Rails rake任务:在一行上接受局部变量,但在下一行拒绝它

时间:2012-07-17 13:11:30

标签: ruby-on-rails

我正在开发一个rake任务,用于更改控制器中定义的元标记。我找到了一些帮助here,但我仍然收到错误。当我尝试运行这个rake任务时,ruby不喜欢第11行,即第一行“found =”。我收到了这个错误。

rake aborted!
undefined local variable or method `line' for main:Object
/Users/********/lib/tasks/meta_tags.rake:11:in `block (2 levels) in <top (required)>'

这就是任务的样子。我很困惑为什么在前一行(10)上正确解释“line”,但是在11上爆炸。任何想法?

require 'rake'
namespace :meta_tags do
  desc 'changes the meta tags'
  task :update => :environment do  
    regex = /^@meta_tag/
    found = false
    file = File.open('app/controllers/site_controller.rb', 'w')
    file.each_line |line|
      replace_line(line) if(found)
      found = true if(line =~ regex)
    end

    def replace_line(line)
      meta_tags = MetaTag.all.map { |tag| tag["tag"] }
      new_tag = meta_tags.sample(1)[0]
      line = "@meta_tag = #{new_tag}"
    end
end

1 个答案:

答案 0 :(得分:2)

你忘了在你的迭代中添加do ...不确定它是否相关,但ruby解释器有时会抛出奇怪的错误:

file.each_line do |line|
  replace_line(line) if(found)
  found = true if(line =~ regex)
end

<强>更新

此外,您似乎需要关闭任务块:

require 'rake'
namespace :meta_tags do
  desc 'changes the meta tags'
  task :update => :environment do  
    regex = /^@meta_tag/
    found = false
    file = File.open('app/controllers/site_controller.rb', 'w')
    file.each_line do |line|
      replace_line(line) if(found)
      found = true if(line =~ regex)
    end
  end

  def replace_line(line)
    meta_tags = MetaTag.all.map { |tag| tag["tag"] }
    new_tag = meta_tags.sample(1)[0]
    line = "@meta_tag = #{new_tag}"
  end
end