def block in rake task

别说谁变了你拦得住时间么 提交于 2019-12-20 09:32:46

问题


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

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? && !@spot.address.blank?
      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

回答1:


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:

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? && !@spot.address.blank?
      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



回答2:


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

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!).

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.

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



来源:https://stackoverflow.com/questions/7298088/def-block-in-rake-task

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!