TheInternet.is_a?(Hash) == true
August 14th, 2006
While convalescing from a recent surgery, I had a flash of insight. One can view the Internet and a file system as one big, really big, Hash.
What is a Hash if not a way to access a value referenced by a key ?
What is a filename ? A key.
What is a URL ? A key.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
require 'uri' require 'open-uri' require 'singleton' # Access the Internet through a Hash-like interface # Code originally written by # François Beausoleil (francois@teksol.info) # This code is released in the public domain. class TheInternet include Singleton def [](url) uri = url.respond_to?(:read) ? url : URI.parse(url) uri.read end def []=(url, value) # POST, PUT or whatever to URL end end |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
require 'singleton' # Access the filesystem through a Hash-like interface # Code originally written by # François Beausoleil (francois@teksol.info) # This code is released in the public domain. class Filesystem include Singleton def [](path) File.read(path) end def []=(path, value) File.open(path, 'wb') do |f| f.write(value) # Could do fancy stuff here: # YAMLize value, marshall it, etc. end end end |
The above allows us to do very interesting things:
1 2 3 4 5 6 7 8 9 |
# Copy from the Internet to a local file: Filesystem.instance['teksol.info/index.html'] = TheInternet.instance['http://blog.teksol.info/'] # Given a suitable implementation of TheInternet#[]=, # we could do: search_results = (TheInternet.instance['http://www.google.com/search'] = {:hl => 'en', :q => 'rails'}) |
Is this rambling interesting ? Certainly. Is it useful ? You tell me !
DISCLAIMER: The Filesystem object above is full of security holes. It should be implemented in a chrooted, environment, check permissions, etc.