在Rake任务中访问模型和模块方法

问题描述 投票:0回答:1

运行Rake任务时访问模块方法时遇到一些麻烦,我现在遇到的错误是

rake aborted!
NameError: uninitialized constant CustomerTestimonialGrabber

我已经将我的模块设置为这样的类

require 'open-uri'
require 'nokogiri'

module CustomerTestimonialGrabber
  class Grabber

    def perform
      get_testimonials
   end

   def get_testimonials
     url = 'http://www.ratedpeople.com/profile/lcc-building-and-construction'
     doc = Nokogiri::HTML.parse(open url)

     testimonial_section = doc.css('.homeowner-rating.content-block:not(.main-gallery):not(:last-child)').each do |t|
      title = t.css('h4').text.strip
      comment = t.css('q').text.strip
      author = t.css('cite').text.strip
     end
    Testimonial.where(title: title, comment: comment, author: author).first_or_create!
   end
 end
end

我的Rake任务设置为我通常的状态

namespace :grab do
  task :customer_testimonials => :environment do
    CustomerTestimonialGrabber::Grabber.new.perform
  end
end

任何人都可以解释为什么我无法访问该模块,我也在我的application.rb文件中进行了设置

config.autoload_paths += %W(#{config.root}/lib)

编辑

我已经完成了一些阅读,现在在运行我的rake任务之前需要该模块

require './lib/customer_testimonial_grabber/grabber.rb'

但是现在看来我无法访问模型本身

NameError: undefined local variable or method `title' for #<CustomerTestimonialGrabber::Grabber:0x00000004be3878>
ruby-on-rails ruby ruby-on-rails-4 methods rake
1个回答
1
投票

也许您应该将推荐行放在前面的方框内?

testimonial_section = doc.css('.homeowner-rating.content-block:not(.main-gallery):not(:last-child)').each do |t|
      title = t.css('h4').text.strip
      comment = t.css('q').text.strip
      author = t.css('cite').text.strip
      Testimonial.where(title: title, comment: comment, author: author).first_or_create!   
end

因为标题未在其外部定义。

© www.soinside.com 2019 - 2024. All rights reserved.