之前我从未使用过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('.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
配置/ schedule.rb
every 1.day, :at => "12:00pm" do
runner "Task.scrape"
end
答案 0 :(得分:0)
它看起来不像任何参数。别忘了控制器只是Ruby对象:
EntriesController.new.scrape
答案 1 :(得分:0)
将代码移动到单独的文件中,并在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
控制器的代码:
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