2010/6/30 Brian Candler <b.candler / pobox.com>:
> Robert Klemme wrote:
>>> It's Ruby. You can always patch or alias_method_chain the target code if
>>> you're willing to bear some slight brittleness.
>>
>> Is this always possible? Wouldn't you need some knowledge of the
>> inner workings of the target code? In this case for example, does it
>> open the file with File.open or maybe with File.foreach?
>
> You simply find that part of the code, and replace the offending
> method(s) with something else. In the limit, you replace everything with
> your own code :-)

That's what I always wanted to do - seems I have to resurrect my
WorldDomination gem. :-)

> It would be convenient to be able to mock out File and Dir with a
> virtual, in-RAM filesystem. I'm not aware of a library which does that,
> but in principle I think it could be done.

Well, /tmp is in memory on many systems and writing a small file is
also a mostly in memory operation.  Of course, this is not as cheap as
doing it completely in userland but probably sufficient for many
applications (although it's not really nice).  At least one can use
Tempfile for this, e.g.

Tempfile "prefix", "/tmp" do |io|
  io.write everything

  io.seek 0
  whatever_load_routine io
end

>> This is an interesting point of interface design: usually it is more
>> convenient to just pass a file name somewhere and that method opens
>> the file (or URL) and reads the data. But from a modularity point of
>> view it is generally better to pass an open IO like instance.
>
> Definitely. The original csv.rb in ruby 1.8 got this very badly wrong.
>
> The new (faster_csv) interface is capable of this, but it suffers from
> missing documentation. IIRR you have to do something like
>
> FasterCSV.new($stdin).each do |row|
> p row
> end
>
> Since the documented "primary" interface is
> FasterCSV.foreach("path/to/file.csv"), you have to dig through the code
> to work out how to handle an open stream.

Or have the idea to look at "ri CSV.new"...

Thanks for the hint.  This is good to know.

Cheers

robert

-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/