【问题标题】:Accessing model and module methods in Rake task在 Rake 任务中访问模型和模块方法
【发布时间】:2014-09-10 09:15:44
【问题描述】:

在运行我的 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>

【问题讨论】:

  • “模特”是什么意思?我在这里看不到任何从 Active Record 继承的东西。您的错误是因为您试图在 Grabber 类上调用 title 方法,但它没有该方法。哪一行触发了该错误?

标签: ruby-on-rails ruby ruby-on-rails-4 methods rake


【解决方案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

因为标题没有在它之外定义。

【讨论】:

    猜你喜欢
    • 2012-02-16
    • 1970-01-01
    • 2011-07-13
    • 1970-01-01
    • 2012-06-04
    • 1970-01-01
    • 1970-01-01
    • 2021-02-05
    • 2010-10-26
    相关资源
    最近更新 更多