【问题标题】:Running into "uninitialized constant" with whenever gem每当 gem 遇到“未初始化的常量”
【发布时间】:2017-03-09 21:11:12
【问题描述】:

今天尝试使用whenever gem。遇到这个错误uninitialized constant EntriesController::RedditScrapper ...我该如何解决这个问题?

当前控制器

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

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

config/schedule.rb

RAILS_ROOT = File.expand_path(File.dirname(__FILE__) + '/')

every 2.minutes do 
  runner "RedditScrapper.scrape", :environment => "development"
end

请帮我找出正确的跑步者任务来写...

Application.rb

require_relative 'boot'

require 'rails/all'

Bundler.require(*Rails.groups)

module ScrapeModel
  class Application < Rails::Application
   config.autoload_paths << Rails.root.join('lib')
  end
end

【问题讨论】:

  • 使用@spickermann 解决方案并在 schedule.rb 中使用RedditScrapper.scrape 而不是调用控制器。

标签: ruby-on-rails ruby cron whenever


【解决方案1】:

Rails 不会自动加载 lib 文件夹。您需要将以下行添加到您的config/application.rb

config.autoload_paths << Rails.root.join('lib')

【讨论】:

  • 上面的config/application.rb 是否正确?另外,我更新了其他文件...
  • @spikermann,好吧,这似乎有效,因为我不再收到该错误......所以是的。有其他问题,但会为它创建一个单独的问题帖子......谢谢。
  • 是的,您的application.rb 看起来不错。
  • 顺便说一句,你怎么知道 Rails 不会自动加载 lib 文件夹?
  • 因为这是一个常见问题,Rails 更改了其自动加载 lib 文件夹的行为。它在 Rails 3.2 之前是这样,而在 Rails 4.0 之后就没有了
【解决方案2】:

据我所知,您已将 RedditScrapper 定义为模块,但您正试图将其用作类...(即在其上调用方法)。

您可以:将其转换为一个类(只需将module 更改为class)或将所有相关方法定义为module_functions

鉴于您选择的用法,前者可能更可取。

【讨论】:

  • 我该怎么做?早些时候它是runner "RedditScrapper.scrape" .. 但遇到了问题...所以将其更改为runner "EntriesController.new.scrape", :environment =&gt; "development" ...
  • 即,我这样称呼它吗? Module.RedditScrapper.scrape?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多