在Rails中不能要求’nokogiri’(但在irb中工作)

我刚刚开始使用Ruby on Rails,到目前为止它工作得很好。 我现在正在尝试实现一个gem,但它不起作用,我希望它只是一个初学者的错误 – 我尚未掌握的东西!

我已经按照教程并获得了我的hello world示例 – 也设法将git推送到我的Heroku帐户。 我开始按照这里的教程: http : //railscasts.com/episodes/190-screen-scraping-with-nokogiri并在终端中使用以下代码(在mac上)

require 'rubygems' require 'nokogiri' require 'open-uri' url = "http://www.walmart.com/search/search-ng.do?search_constraint=0&ic=48_0&search_query=batman&Find.x=0&Find.y=0&Find=Find" doc = Nokogiri::HTML(open(url)) puts doc.at_css("title").text 

所以这很好用。 我可以在终端内看到标题。 但是,当我尝试将此代码放在我的视图控制器中时,它找不到nokogiri gem。 我的控制器中的代码是

 class HomeController < ApplicationController def index require 'rubygems' require 'nokogiri' require 'open-uri' url = "http://www.walmart.com/search/search-ng.do?search_constraint=0&ic=48_0&search_query=batman&Find.x=0&Find.y=0&Find=Find" doc = Nokogiri::HTML(open(url)) @mattVar = doc.at_css("title").text end end 

那么在我的HTML中,我有

 

Hello!

哪个应该在终端窗口中输出标题。 但是,我得到一个错误,说no such file to load -- nokogiri

我出错的任何想法?
如果我做gem list我可以看到那里的nokogirigem。


UPDATE

我关闭了本地rails服务器并重新启动。 它现在正在运作。 不确定是不是因为工作将gem添加到我的root或执行’bundle install’(如下面建议的post)。 谢谢您的帮助。

首先尝试将控制器更改为类似的东西

 class HomeController < ApplicationController require 'nokogiri' require 'open-uri' def index url = "http://www.walmart.com/search/search-ng.do?search_constraint=0&ic=48_0&search_query=batman&Find.x=0&Find.y=0&Find=Find" doc = Nokogiri::HTML(open(url)) @mattVar = doc.at_css("title").text end end 

我猜你也在使用bundler,检查你是否包含了这个gem并运行bundle install。

您可以在http://gembundler.com/找到相关文档。

  1. 您应该将各种require语句放在index方法之外。 将它们放在那里不会减慢你的速度,但是你要求Ruby确保每次调用方法时它们都被加载。 最好在代码顶部只需要一次。 但是,这不会导致您的问题。

  2. 我怀疑您在不同于IRB运行的环境下测试服务器。暂时尝试删除有问题的require语句并将HTML模板更改为:

     

    Environment

    • Ruby: <%=RUBY_VERSION%>
    • Gems: <%=`gem list`%>