随时随地进入“未初始化的常量”

时间:2017-03-09 21:11:13

标签: ruby-on-rails ruby cron whenever

今天尝试使用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

配置/ 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

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:0)

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

您可以:将其转换为课程(只需将module更改为class)或将所有相关方法定义为module_function s

根据您的选择,前者可能更可取。