Call methods from a task in Rake files

2020-07-18 02:49发布

It is possible to call a method which is in the same rake file as the task? In the code below you can see that I have the method call get_search_url which will be assigned to url.

namespace :populate do
desc "ETC"
task :db => :environment do

    Report.where(link: "").each do |word|
        url = get_search_url(word.name)
        doc = Nokogiri::HTML(open(url))
        word.update_columns(link: link)
    end
end

def get_search_url(keyword)
    return "URL/keyword"
end

end

2条回答
家丑人穷心不美
2楼-- · 2020-07-18 03:16

However if you define the same method in two different rake tasks, they will both be globally loaded when running rake, and one of the method definitions will be redefined / overwritten by the other!

Better practice is to define methods in a separate module and then include that module in your rake file. See https://kevinjalbert.com/defined_methods-in-rake-tasks-you-re-gonna-have-a-bad-time/ (Solution #3)

查看更多
Ridiculous、
3楼-- · 2020-07-18 03:25

Yes it is absolutely possible. Just define those methods after the namespace ;)

namespace :populate do
desc "ETC"
task :db => :environment do

    Report.where(link: "").each do |word|
        url = get_search_url(word.name)
        doc = Nokogiri::HTML(open(url))
        word.update_columns(link: link)
    end
end

end

def get_search_url(keyword)
    return "URL/keyword"
end
查看更多
登录 后发表回答