Is there a single way to get content in a file: // or http: // URI scheme in Ruby?

It seems that the Net :: HTTP library does not support loading a local file through the file: //. I want to configure the loading of content from a file or remotely, depending on the environment.

Is there a standard Ruby way to access any type in the same way, or is there a prohibition on having some kind of concise code that is being run?

+4
source share
3 answers

Do you know about open-uri ?

require 'open-uri' open("/home/me/file.txt") { |f| ... } open("http://www.google.com") { |f| ... } 

Therefore, to support "http: //" or "file: //" in one of the statements, simply delete "file: //" from the beginning of the uri, if it is present (and there is no need to do any processing for "http: //") , eg:

 uri = ... open(uri.sub(%r{^file://}, '')) 
+3
source

As Ben Lee noted, open-uri is the way to go here. I also used it in combination with paperclip to store model related resources, which makes everything brilliantly simple.

 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 
0
source

Here is some experimental code that teaches open-uri to process a file: URIs:

 require 'open-uri' require 'uri' module URI class File < Generic def open(*args, &block) ::File.open(self.path, &block) end end @@schemes['FILE'] = File end 
0
source

All Articles