Skip to content

Instantly share code, notes, and snippets.

@trans
Created June 24, 2009 09:44
Show Gist options
  • Save trans/135127 to your computer and use it in GitHub Desktop.
Save trans/135127 to your computer and use it in GitHub Desktop.
Fetch File from Disk or Web
# This is the first reusable ruby lib I ever wrote.
# It is pretty useless now, and in hindsight not so well
# written either, but I've gist it for posterity.
# TomsLib - Tom's Ruby Support Library
# Copyright (c) 2002 Thomas Sawyer, LGPL
#
# FetchFile
#
# For purposes of this library a url is defined as both
# the typical idea of a url and a local filepath as well.
require "net/http"
# pulling this down from apache?
#if ENV['DOCROOT']
# DOCPATH = ENV['DOCROOT'] + ENV['PATH_INFO'].gsub(/\/[\w.()]*$/, '')
#else
# DOCPATH = File.expand_path('.')
#end
module TomsLib
module FileFetch
# Returns a string from url or string
def fetch_xml(url_or_string)
case url_or_string
when /^\s*</ # if xml string
return url_or_string.strip
when /^http:\/\// # if http url
return fetch_http(url_or_string)
when /^file:(.*)/ # if file url
return fetch_local($1)
else # if file path
return fetch_local(url_or_string)
end
end
# Returns a string read from a url or file path
def fetch_url(url)
case url
when /^http:\/\// # if http url
return fetch_http(url)
when /^file:(.*)/ # if file url
return fetch_local($1)
else # if file path
return fetch_local(url)
end
end
# Returns the document as a string refered to by an http url.
def fetch_http(http_url)
url = http_url
if url !~ /^http:\/\//
url += "http://#{http_url}"
end
url =~ /^http:\/\//
addr, path = $'.split("/", 2)
host, port = addr.split(":")
Net::HTTP.start(host, (port||80).to_i) do |sess|
res = ""
sess.get("/" + (path || ""), nil, res)
return sess
end
end
# Returns the document as string refered to by a local pathname.
def fetch_local(local_url)
#if is_relative?(local_url)
# fp = DOCPATH + "/" + local_url
#else
fp = local_url
#end
return File.readlines(fp.untaint).to_s
end
# Return true if path is relative
def is_relative?(url)
case url
when /^http:\/\// # if http url
return false
when /^ftp:\/\// # if ftp url
return false
when /^file:(.*)/ # if file url
fp = $1
else # if file path
fp = url
end
return (fp[0..0] != "/")
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment