[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Path management in ruby

zimba.tm@gmail.com

3/6/2006 9:42:00 AM

Hi list,

While playing and coding with ruby, I found it often useful to have a better
way to handle paths that in the actual version. I think it would be nice to
have an unified way to manage paths.

$:.class => Array
ENV['PATH'] => String

<code>
class Path < Array
def initialize(path = nil)
if path.kind_of? String
paths = path.split(':')
paths.each do |p|
push p
end
elsif path.kind_of? Array
path.each do |p|
push p
end
end
end

def find(filename, ext=nil)
each do |path|
filepath = File.join(path, filename)
return filepath if File.exist?( filepath )
if ext
filepath = File.join(path, filename + ext)
return filepath if File.exist?( filepath )
end
end
return nil
end
alias :include? find

# TODO : The join symbol changes between the platforms. Make this dependent
of the platform.
def to_s
join(':')
end

end

p = Path.new($:)
p.include? 'ipaddr.rb'
=> "/usr/lib/ruby/1.8/ipaddr.rb"
</code>

--
Cheers,
zimba.tm

weblog : http://zim...


1 Answer

Payton Swick

3/7/2006 2:15:00 PM

0

Have you seen the Pathname and Pathname2 modules? They're part of the
standard library. They are also platform independant and give you all
the features of File, FileUtils, and more.

-Payton

zimba.tm wrote:
> Hi list,
>
> While playing and coding with ruby, I found it often useful to have a better
> way to handle paths that in the actual version. I think it would be nice to
> have an unified way to manage paths.
>
> $:.class => Array
> ENV['PATH'] => String
>
> <code>
> class Path < Array
> def initialize(path = nil)
> if path.kind_of? String
> paths = path.split(':')
> paths.each do |p|
> push p
> end
> elsif path.kind_of? Array
> path.each do |p|
> push p
> end
> end
> end
>
> def find(filename, ext=nil)
> each do |path|
> filepath = File.join(path, filename)
> return filepath if File.exist?( filepath )
> if ext
> filepath = File.join(path, filename + ext)
> return filepath if File.exist?( filepath )
> end
> end
> return nil
> end
> alias :include? find
>
> # TODO : The join symbol changes between the platforms. Make this dependent
> of the platform.
> def to_s
> join(':')
> end
>
> end
>
> p = Path.new($:)
> p.include? 'ipaddr.rb'
> => "/usr/lib/ruby/1.8/ipaddr.rb"
> </code>
>