Cannot require 'nokogiri' in Rails (but works in irb)

醉酒当歌 提交于 2019-12-02 03:27:21

Firstly try changing your controller to be somthing like

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

I'm guessing you are also using bundler, check that you have include this gem and run bundle install.

You can find the documentation for this at http://gembundler.com/

  1. You should put your various require statements outside of your index method. It won't slow you down much to have them in there, but you're asking Ruby to ensure that they are loaded every time the method is called. Better to just require them once at the top of your code. This won't cause your problem, however.

  2. I suspect that you are testing your server under a different environment than what IRB is running in. Try removing the offending require statements for the moment and changing your HTML template to:

    <h1>Environment</h1>
    <ul>
      <li>Ruby: <%=RUBY_VERSION%></li>
      <li>Gems: <%=`gem list`%></li>
    </ul>
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!