Ruby-on-rails rake 任务中的 def 块

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7298088/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 01:55:24  来源:igfitidea点击:

def block in rake task

ruby-on-railsrubymethodsrake

提问by Victor

I got undefined local variable or method 'address_geo' for main:Objectwith the following rake task. What's the problem with it?

我得到undefined local variable or method 'address_geo' for main:Object了以下耙任务。它有什么问题?

include Geokit::Geocoders

namespace :geocode do
  desc "Geocode to get latitude, longitude and address"
  task :all => :environment do
    @spot = Spot.find(:first)
    if @spot.latitude.blank? && [email protected]?
      puts address_geo
    end

    def address_geo
      arr = []
      arr << address if @spot.address
      arr << city if @spot.city
      arr << country if @spot.country
      arr.reject{|y|y==""}.join(", ")
    end
  end
end

回答by rubyprince

You are defining the method inside the rake task. For getting the function, you should define outside the rake task (outside the task block). Try this:

您正在定义 rake 任务中的方法。为了获得该函数,您应该在 rake 任务之外(在任务块之外)定义。尝试这个:

include Geokit::Geocoders

namespace :geocode do
  desc "Geocode to get latitude, longitude and address"
  task :all => :environment do
    @spot = Spot.find(:first)
    if @spot.latitude.blank? && [email protected]?
      puts address_geo
    end
  end

  def address_geo
    arr = []
    arr << address if @spot.address
    arr << city if @spot.city
    arr << country if @spot.country
    arr.reject{|y|y==""}.join(", ")
  end
end

回答by Hula_Zell

Careful: Methods defined in rake files end up defined on the global namespace.

小心:在 rake 文件中定义的方法最终定义在全局命名空间中。

I would propose to extract the methods into a module or class. This is because methods defined in rake files end up defined on the global namespace. i.e. they can then be called from anywhere, not just within that rake file (even if it is namespaced!).

我建议将方法提取到模块或类中。这是因为在 rake 文件中定义的方法最终在全局命名空间中定义。即它们可以从任何地方调用,而不仅仅是在那个 rake 文件中(即使它是命名空间的!)。

This also means that if you have two methods with the same name in two different rake tasks, one of them will be overwritten without you knowing it. Very deadly.

这也意味着如果您在两个不同的 rake 任务中有两个同名的方法,其中一个将在您不知情的情况下被覆盖。非常致命。

A great explanation is available here: https://kevinjalbert.com/defined_methods-in-rake-tasks-you-re-gonna-have-a-bad-time/

这里有一个很好的解释:https: //kevinjalbert.com/defined_methods-in-rake-tasks-you-re-gonna-have-a-bad-time/