在模型中使用 Nokogiri 时出错
Error when using Nokogiri within model
我正在尝试开发一种模型方法,该方法将从对控制器的 post 请求中获取 url。虽然我能够从控制器成功使用 Nokogiri,但当我尝试将逻辑移入模型时,我总是收到错误消息:
Errno::ENOENT:没有这样的文件或目录@rb_sysopen - "www.url.com"
为什么 Rails 不允许我在模型中实现 Nokogiri?
The model method I have setup as:
require 'nokogiri'
require 'open-uri'
class UrlContent < ApplicationRecord
validates :content, presence: true
def self.parser(url)
binding.pry
html = open(url)
doc = Nokogiri::HTML(html)
content = doc.css('h1, h2, h3, a').map(&:text).join(" ")
content
end
end
我的控制器看起来像:
require 'nokogiri'
require 'open-uri'
class UrlContentsController < ApplicationController
skip_before_filter :verify_authenticity_token
def create
content = UrlContent.parser(params[:content])
binding.pry
render layout: false
end
def index
@url_contents = UrlContent.all
render json: @url_contents, status: 200, layout: false
end
end
看起来您正在用您认为是 URL 但实际上不是的内容调用 open
。你这样说:
html = open(url)
并且您收到关于 open
无法找到名为 'www.url.com'
的 文件 的投诉,所以您实际上是在说:
html = open('www.url.com')
当你的意思更像是:
html = open('http://www.url.com')
您应该检查您的 URL 并添加方案(如果它们还没有)。我通常将 Addressable 用于此类事情,如下所示:
uri = Addressable::URI.parse(url)
url = "http://#{url}" if(!uri.scheme)
我正在尝试开发一种模型方法,该方法将从对控制器的 post 请求中获取 url。虽然我能够从控制器成功使用 Nokogiri,但当我尝试将逻辑移入模型时,我总是收到错误消息:
Errno::ENOENT:没有这样的文件或目录@rb_sysopen - "www.url.com"
为什么 Rails 不允许我在模型中实现 Nokogiri?
The model method I have setup as:
require 'nokogiri'
require 'open-uri'
class UrlContent < ApplicationRecord
validates :content, presence: true
def self.parser(url)
binding.pry
html = open(url)
doc = Nokogiri::HTML(html)
content = doc.css('h1, h2, h3, a').map(&:text).join(" ")
content
end
end
我的控制器看起来像:
require 'nokogiri'
require 'open-uri'
class UrlContentsController < ApplicationController
skip_before_filter :verify_authenticity_token
def create
content = UrlContent.parser(params[:content])
binding.pry
render layout: false
end
def index
@url_contents = UrlContent.all
render json: @url_contents, status: 200, layout: false
end
end
看起来您正在用您认为是 URL 但实际上不是的内容调用 open
。你这样说:
html = open(url)
并且您收到关于 open
无法找到名为 'www.url.com'
的 文件 的投诉,所以您实际上是在说:
html = open('www.url.com')
当你的意思更像是:
html = open('http://www.url.com')
您应该检查您的 URL 并添加方案(如果它们还没有)。我通常将 Addressable 用于此类事情,如下所示:
uri = Addressable::URI.parse(url)
url = "http://#{url}" if(!uri.scheme)