Search code examples
ruby-on-railsrubyruby-on-rails-4methodsrake

Accessing model and module methods in Rake task


I am having some trouble accessing my module methods when running my Rake task, the error I get at the moment is

rake aborted!
NameError: uninitialized constant CustomerTestimonialGrabber

I have set my module with class like so

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

My Rake task is set how I would normally

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

Could anyone explain why I am not able to access the module, I have also set this in my application.rb file

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

Edit

I have done some more reading and have now required the module before running my rake task

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

but now it seems I have trouble accessing the model itself

NameError: undefined local variable or method `title' for #<CustomerTestimonialGrabber::Grabber:0x00000004be3878>

Solution

  • maybe you should put the Testimonial line INSIDE the preceding block?

    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
    

    Because title isn't defined outside of it.