Nicholas Frechette
10/15/2006 1:19:00 PM
Hi, I'm currently working on a side project which has me store binary
content in memory.
In order to make it's use as transparent as possible, i overloaded the
'require' method to search as well in the memory and this works fine at
the moment. In the same line of thought, I tried changing the way
File.new works to return a StringIO object pointing to my binary data in
memory instead of an ordinary IO object... However, i ran into an
interesting problem. Consider the following code:
class File
alias_method :old_new, :initialize
def initialize(*args)
if args[0] == 'a.txt'
# Do not return a file object, return say, a Hash
Hash.new
else
old_new(*args)
end
end
end
o = File.new('a.txt')
puts "Object is of class: #{o.class}"
This outputs:
Object is of class: File
Obviously. Now, looking further for alternatives, i tried to overload
Class.new. Consider the following code:
class Foo
end
class Bar
end
class Class
alias oldNew new
def new(*args)
print "Creating a new ", self.name, "\n"
if self.name == 'File'
require 'stringio'
StringIO.new('This is a string!','r')
elsif self.name == 'Foo'
Bar.new
else
oldNew(*args)
end
end
end
d = Foo.new
puts "Should be type Foo and is: #{d.class}"
n = File.new('lol.rb','r')
puts "Should be type StringIO and is: #{n.class}"
puts "Content is: #{n.read}"
With a file named lol.rb in my path with the single line of content:
"Hello", this outputted:
Creating a new Foo
Creating a new Bar
Should be type Foo and is: Bar
Should be type StringIO and is: File
Content is: Hello
==========================
Two things here:
Class.new is working as expected with Foo, returning a Bar object. But,
when File.new is called, Class.new is not called as it was for Foo.new!
Any thoughts/help please? I have ran out of ideas... An obvious solution
is to use a different constructor that is not File.new but that would
make it not very elegant.
Thanks and regards.
Nicholas