How to load a Ruby gem into a module

653 views Asked by At

I am trying to write a web scraper using Watir that can be run on a schedule.

My module is called PriceScraperModule but it is not loading. I get this error:

NameError (uninitialized constant PriceScraperModule::Watir)

My module looks like:

module PriceScraperModule
  
  def self.scrape
    browser = Watir::Browser.new
  end
end

My Gemfile includes:

gem 'watir'
gem 'webdrivers'

When I try requiring it, it doesn't work either:

module PriceScraperModule
  require 'watir'
  
  def self.scrape
    browser = Watir::Browser.new
  end
end

I get this error:

LoadError (cannot load such file -- watir)

What should I do?

3

There are 3 answers

1
Rajagopalan On

I have written the following code and it's working properly.

require 'watir'
module PriceScraperModule
  def self.scrape
    b = Watir::Browser.new
    b.goto 'www.google.com'
  end
end

PriceScraperModule.scrape
0
Noel Delgado On

Fixed it. In your terminal, run

$ spring stop
0
Kamal Panhwar On

I was just checking as I did comment with perspective of Rails but you are not using rails so in case if you want to use it as a individual ruby project with bundler following will work.

Gemfile

# frozen_string_literal: true

source 'https://rubygems.org'

git_source(:github) { |repo_name| "https://github.com/#{repo_name}" }

gem 'watir'
gem 'webdrivers'

your module price_scraper_module.rb file

module PriceScraperModule
  require 'watir'

  def self.scrape
    browser = Watir::Browser.new
    browser.goto 'www.google.com'
  end
end

and now any file where you want to use I am using sample.rb

#!/usr/bin/ruby
$LOAD_PATH << '.'
require 'price_scraper_module'
include PriceScraperModule

PriceScraperModule.scrape

Now just run following commands to get all Gems

bundle

and to run the sample

ruby sample

Although your one file is perfectly working, in case you want to make it part of an individual project with Gemfile.