Order some files by time before display

D

David B.

Hi everybody,

I have write a short script that display each article of a folder:

require 'find'
result = []
@pattern = '*.html'
Find.find('public/2008/') do |p|
next unless File.file?(p)
name = File.basename(p)
result << p if File.fnmatch(@pattern, name)
end
a = ''
result.length.times do |i|
content = File.read(result)
a += '<div class="article">'
a += content
a += '<address>' + File.ctime(result).to_s + '</address>'
a += '</div>'
end
a

As you can see, it display some articles in a webpage. However, but I
would like to order them by time (with File.ctime(result) for
instance) such as in blogs. If you see a sexy way to do so, that would
be very helpful for me.

Thanks,
Dendicus
 
M

Matthias Reitinger

Hi David,
require 'find'
result = []
@pattern = '*.html'
Find.find('public/2008/') do |p|
next unless File.file?(p)
name = File.basename(p)
result << p if File.fnmatch(@pattern, name)
end

No need for 'find'. A simple 'glob' suffices:

files = Dir[File.join('public/2008/', '**', @pattern)]
a = ''
result.length.times do |i|
content = File.read(result)
a += '<div class="article">'
a += content
a += '<address>' + File.ctime(result).to_s + '</address>'
a += '</div>'
end
a


Iterating over an array like this is kind of cumbersome. 'each' should
be your weapon of choice here. Furthermore using the << operator for
concatenation could yield in better performance as += constructs a new
String object whereas << doesn't (AFAIK).
As you can see, it display some articles in a webpage. However, but I
would like to order them by time (with File.ctime(result) for
instance) such as in blogs. If you see a sexy way to do so, that would
be very helpful for me.


Hope that's sexy enough for you:

result = result.sort_by { |p| File.ctime(p) }

To sum it all up here is how I would have done it:

---
@dir = 'public/2008'
@pattern = '*.html'

files = Dir[File.join(@dir, '**', @pattern)].select { |f| File.file?(f)
}
files = files.sort_by { |f| File.ctime(f) }

a = ''
files.each do |f|
a << '<div class="article">'
a << File.read(f)
a << '<address>' + File.ctime(f).to_s + '</address>'
a << '</div>'
end
a
---

Hope that helps!

Regards,
Matthias
 
D

David B.

Many thanks, Matthias! Your answer was perfectly resolve my problem and
now the code is really more fashion!

Thanks again,
Dendicus
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,163
Latest member
Sasha15427
Top