是否有统一的方法来获取 Ruby 中 file:// 或 http:// URI 方案的内容?
看来 Net::HTTP 库不支持通过 file:// 加载本地文件。我想根据环境配置从文件或远程加载内容。
是否有标准的 Ruby 方法可以以相同的方式访问任一类型,或者禁止一些简洁的分支代码?
It appears the Net::HTTP library doesn't support loading of local file via file:// . I'd like to configure loading of content from a file or remotely, depending on environment.
Is there a standard Ruby way to access either type the same way, or barring that some succinct code that branches?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(3)
痴情2024-12-13 15:04:31
正如 Ben Lee 指出的那样, open-uri 就是这样去这里。我还将它与 paperclip 结合使用来存储与模型相关的资源,这使一切变得非常简单。
require 'open-uri'
class SomeModel < ActiveRecord::Base
attr_accessor :remote_url
has_attached_file :resource # etc, etc.
before_validation :get_remote_resource, :if => :remote_url_provided?
validates_presence_of :remote_url, :if => :remote_url_provided?,
:message => 'is invalid or missing'
def get_remote_resource
self.resource = SomeModel.download_remote_resource(self.remote_url)
end
def self.download_remote_resource (uri)
io = open(URI.parse(uri))
def io.original_filename; base_uri.path.split('/').last; end
io.original_filename.blank? ? nil : io
rescue
end
end
# SomeModel.new(:remote_url => 'http://www.google.com/').save
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
你知道 open-uri 吗?
因此,要在一个语句中支持“http://”或“file://”,只需从 uri 的开头删除“file://”(如果存在)(并且无需对“ http://"),像这样:
Do you know about open-uri?
So to support either "http://" or "file://" in one statement, simply remove the "file://" from the beginning of the uri if it is present (and no need to do any processing for "http://"), like so: