我刚刚开始使用 Ruby on Rails,到目前为止它运行良好。我现在正在尝试实现一个 gem,但它不起作用,我希望这只是一个初学者的错误——我还没有掌握的东西!!
我已经学习了教程并获得了我的 hello world 示例 - 还设法将其 git push 到我的 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
这样效果很好。我可以在终端内看到标题。但是,当我尝试将此代码放入我的 View Controller 时,它找不到 nokogiri gem。我的 Controller 中的代码是
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 中,我有
<h1>Hello!</h1>
<p><%= @mattVar %></p>
哪个应该像在终端窗口中那样输出标题。但是,我收到一条错误消息,提示 no such file to load -- nokogiri
有什么地方出错了吗?
如果我执行 gem list
,我可以在那里看到 nokogiri gem。
更新
我关闭了本地 Rails 服务器并重新启动。它现在正在工作。不确定是因为将 gem 添加到我的根目录还是执行“捆绑安装”(如以下帖子所建议的)。感谢您的帮助。
最佳答案
首先尝试将您的 Controller 更改为类似的东西
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/ 找到相关文档
关于ruby-on-rails - 不能在 Rails 中要求 'nokogiri'(但在 irb 中有效),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6082305/