Ruby on rails 如何运行控制器';在任何时候都要采取行动';s配置/时间表
我以前从未在任何时候使用过Ruby on rails 如何运行控制器';在任何时候都要采取行动';s配置/时间表,ruby-on-rails,ruby,cron,whenever,Ruby On Rails,Ruby,Cron,Whenever,我以前从未在任何时候使用过应用程序。尝试了解如何使用它从控制器运行操作。可能吗 控制器 class EntriesController < ApplicationController def index @entries = Entry.all end def scrape require 'open-uri' doc = Nokogiri::HTML(open("https://www.reddit.com/")) entries = doc.css(
应用程序。尝试了解如何使用它从控制器运行操作。可能吗
控制器
class EntriesController < ApplicationController
def index
@entries = Entry.all
end
def scrape
require 'open-uri'
doc = Nokogiri::HTML(open("https://www.reddit.com/"))
entries = doc.css('.entry')
entriesArray = []
entries.each do |entry|
title = entry.css('p.title > a').text
link = entry.css('p.title > a')[0]['href']
entriesArray << Entry.new({ title: title, link: link })
end
if entriesArray.map(&:valid?)
entriesArray.map(&:save!)
end
respond_to do |format|
format.html { redirect_to entries_url, notice: 'Entries were successfully scraped.' }
format.json { entriesArray.to_json }
end
end
end
看起来它不接受任何参数。不要忘记控制器只是Ruby对象:
EntriesController.new.scrape
将代码移动到单独的文件中,并在schedule.rb和控制器中重新使用它:
# lib/reddit_scrapper.rb
require 'open-uri'
module RedditScrapper
def self.scrape
doc = Nokogiri::HTML(open("https://www.reddit.com/"))
entries = doc.css('.entry')
entriesArray = []
entries.each do |entry|
title = entry.css('p.title > a').text
link = entry.css('p.title > a')[0]['href']
entriesArray << Entry.new({ title: title, link: link })
end
if entriesArray.map(&:valid?)
entriesArray.map(&:save!)
end
end
end
你的回答让我有点困惑。你是说我的跑步者应该是runner“EntriesController.new.scrape”
?@user27307254534534534543675765是的,试一试谢谢。现在刚修改过。但是不知道如何确保它工作?当你说把它放在库
中时,你的意思是单独的,而不是库/任务
正确吗?好的,把它放在库
中,然后复制你的任务。。。我如何确保它工作正常?到目前为止,首页显示的是较旧的reddit内容……为什么这是一个Nokogiri问题?因为代码提到了它?只有在出现问题时才标记,而不仅仅是因为在某个地方提到了问题。你试了什么?当你尝试时发生了什么?它成功了还是失败了?如果失败了,我们需要查看错误。如果没有失败,你为什么要问这个问题?@theTinMan,好吧,谢谢你让我知道我不该提这个问题。我觉得这是个好主意,因为有时候事情会相互影响,有时候可以说,看到“更大的图景”是有帮助的。我不会再这样做了。只会提到与问题相关的标签。如果错误提到了它,那么它是有意义的。代码可以使用许多不同的库或gem,这些库或gem多得不计其数,所以除非它们专门涉及到这个问题,否则不要麻烦它们。
# lib/reddit_scrapper.rb
require 'open-uri'
module RedditScrapper
def self.scrape
doc = Nokogiri::HTML(open("https://www.reddit.com/"))
entries = doc.css('.entry')
entriesArray = []
entries.each do |entry|
title = entry.css('p.title > a').text
link = entry.css('p.title > a')[0]['href']
entriesArray << Entry.new({ title: title, link: link })
end
if entriesArray.map(&:valid?)
entriesArray.map(&:save!)
end
end
end
class EntriesController < ApplicationController
def index
@entries = Entry.all
end
def scrape
RedditScrapper.scrape
respond_to do |format|
format.html { redirect_to entries_url, notice: 'Entries were successfully scraped.' }
format.json { entriesArray.to_json }
end
end
end
every 1.day, :at => "12:00pm" do
runner "RedditScrapper.scrape"
end