… and from the substratum, it arises …
One-liner: scoped_require provides an optional parameter to
Kernel#require to allow you to shove the created modules/classes into
some sandboxy container module. I use it to prevent namespace collision
with an external library. It’s a hack. Heed the version number.
Example usage:
require ‘rubygems’
require_gem ‘rubyful_soup’ # luckily this doesn’t have autorequire
set
require ‘rubyful_soup’, :module => :Soup # here’s the magic
assert_equal ‘constant’, defined? Soup::BeautifulSoup
Browse or get at:
http://opensvn.csie.org/twifkak/trunk/scoped_require/scoped_require.rb
See the unit tests for usage. If you wanna run the unit tests, export
the whole scoped_require directory. And have the rubyful_soup gem
installed. Weirdo.
Several-liner:
So, I was writing a Rails app, and I was using RubyfulSoup to parse in
some documents and feed some metadata into the database. Hoorah. (Thanks
for the library, by the way!)
Then, I decided, “I should implement folksonomy!” As any standard human
would do, I created a model object called Tag, and went on creating my
tagging functionality.
I decide to run all of my tests again. Woo! Big honkin’ error in the
feeder code. See, it seems that RubyfulSoup defines a class called Tag
and shoves it in the top-level space – or, at least, tries to, before
getting a “base class mismatch” error.
Well, I could contact the author and tell him to move his class out of
my way, but I’m antisocial, and besides, I want it to work now! I
could put my class in a module, but I WILL NOT SUCCUMB. No, no, I will
put his classes in a module. And I’ll do it without touching his code.
(Look, ma, no CM issues!)
Well, being the naïve and lazy fellow I am, I try the simplest approach:
module Soup
require ‘rubyful_soup’
end
whimper It doesn’t work. I eventually settle on this can of ugly:
module Soup
eval IO.read(‘sgml_parser.rb’)
$" << ‘sgml_parser.rb’
eval IO.read(‘rubyful_soup.rb’)
end
Yeah. Cry. So I packaged up that can of ugly into a pretty little
#require override, so that I never have to think about it again.
Judging by http://www.rcrchive.net/rcr/show/289, I’m not the only person
who had the desire for this capability. Is this “library” useful to
other people? Would it be, if I got rid of the need for a require_gem
first? Or is this just some weird thing that only helps me? Do you have
suggestions for making it suck less? Is it sad that my test code is
prettier than my real code? Is there a library out there that already
does this, but better? Will I become famous and wealthy thanks to this
library (please oh please oh please)?
Thanks,
Devin
Yeah, I don’t mean to pick on RubyfulSoup so much… 's just on the
brain…