【问题标题】:How to load a Ruby gem into a module如何将 Ruby gem 加载到模块中
【发布时间】:2020-11-16 06:33:55
【问题描述】:

我正在尝试使用 Watir 编写一个可以按计划运行的网络爬虫。

我的模块名为PriceScraperModule,但它没有加载。我收到此错误:

NameError (uninitialized constant PriceScraperModule::Watir)

我的模块看起来像:

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

我的 Gemfile 包括:

gem 'watir'
gem 'webdrivers'

当我尝试要求它时,它也不起作用:

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

我收到此错误:

LoadError (cannot load such file -- watir)

我该怎么办?

【问题讨论】:

  • 这看起来很像 gem 在您的 Gemfile 中,但实际上并没有安装。当您运行bundle info watir 时,响应是什么?如果显示“找不到...”,请运行 bundle install 并再试一次。
  • 尝试评论这一行`需要'watir'`,因为它是宝石所以不需要这一行。
  • @KamalPanhwar,你的这个假设是基于什么?如果此代码不是通过 Rails 调用的,则需要手动 require gem。 require 引发错误而不只是返回 false 的事实告诉我们系统上没有安装 gem。
  • 我已经检查了代码并且没有错误,所以我想也许在 Rails 中他要求提供错误!
  • @KamalPanhwar 这就是我第一次尝试时所做的。它没有 require 行。

标签: ruby-on-rails ruby watir rails-api webdrivers-gem


【解决方案1】:

我只是检查一下,因为我对 Rails 的观点发表了评论,但你没有使用 rails,所以如果你想将它用作带有捆绑器的单个 ruby​​ 项目,以下将起作用。

宝石文件

# frozen_string_literal: true

source 'https://rubygems.org'

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

gem 'watir'
gem 'webdrivers'

你的模块 price_scraper_module.rb 文件

module PriceScraperModule
  require 'watir'

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

现在你想使用的任何文件我都在使用 sample.rb

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

PriceScraperModule.scrape

现在只需运行以下命令即可获取所有宝石

bundle

并运行示例

ruby sample

虽然您的一个文件可以完美运行,但如果您想使用 Gemfile 将其作为单个项目的一部分。

【讨论】:

    【解决方案2】:

    修复它。在您的终端中,运行

    $ spring stop
    

    【讨论】:

      【解决方案3】:

      我已经编写了以下代码,并且运行正常。

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

      【讨论】:

      • 出现同样的错误LoadError (cannot load such file -- watir)
      猜你喜欢
      • 1970-01-01
      • 2013-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-09
      • 1970-01-01
      • 2021-12-31
      相关资源
      最近更新 更多