Ruby is simple? NooooT!

C

Casimir P

Hehe whoever said that ruby is not verbose was WRONG!! ;)

I mean look at the code below!

All this just to find subdirectories and to list all the jpg files inside!!
So... NOT!!! :) I hope the code posts well..

#code starts here
imgpath = "img/"
def seekPhotoDirs(path)
require 'find'
photodirs = Array.new

Find.find(path) do |item|
if FileTest.directory?(item)
if item != path #ei haluta tätä samaa hakemistoa
puts indexImages(item)
end
end
end
return photodirs
end
def indexImages(dir)
dir.each { |d|
Dir.entries(d).each { |filu|
nn = filu.to_s
ext = filu.downcase.split(".").last
if ( ext == "png" || ext == "jpg")
puts filu
end
}
}
end
puts seekPhotoDirs(imgpath)
#code ends here

Greetings to whytheluckystiff! Outfoxed, not sourced.

Csmr
 
R

Robert Dober

Hehe whoever said that ruby is not verbose was WRONG!! ;)

I mean look at the code below!

All this just to find subdirectories and to list all the jpg files inside= !!
So... NOT!!! :) I hope the code posts well..

#code starts here
imgpath =3D "img/"
def seekPhotoDirs(path)
require 'find'
photodirs =3D Array.new

Find.find(path) do |item|
if FileTest.directory?(item)
if item !=3D path #ei haluta t=E4t=E4 samaa hakem= istoa
puts indexImages(item)
end
end
end
return photodirs
end
def indexImages(dir)
dir.each { |d|
Dir.entries(d).each { |filu|
nn =3D filu.to_s
ext =3D filu.downcase.split(".").last
if ( ext =3D=3D "png" || ext =3D=3D "jpg")
puts filu
end
}
}
end
puts seekPhotoDirs(imgpath)
#code ends here

Greetings to whytheluckystiff! Outfoxed, not sourced.

Csmr
Argggh, right now I have to leave the office but I predict that you
will get nice, readable ruby code to do the same in less than 10 lines
*before* I can login again in about three hours.
Folks, do not let me down, pleaaaase ;).

Cheers
Robert


--=20
what do I think about Ruby?
http://ruby-smalltalk.blogspot.com/
 
P

Phlip

Argggh, right now I have to leave the office but I predict that you
will get nice, readable ruby code to do the same in less than 10 lines
*before* I can login again in about three hours.
Folks, do not let me down, pleaaaase ;).

Should we start with Pathname?

(And note that super-terse code is not a virtue - it should be a
little readable...)
 
C

Casimir P

files = Dir["img/**/*.jpg"]

Well technically that does NOT find subdirectories. Call in the
disqualifier dogs!!!!!!

Allow me to draw your attention to the **

It sweeps subfolders.
But supposedly you cant tell whats what now. Its all just a big blur. You
get all the little images but lose the bigger picture.

Its what happens when you dont keep track of the subdirectories.

Csrm
 
B

Bill Kelly

From: "Tim McIntyre said:
files = Dir.glob("img/**/*.jpg")

pretty sure that keeps all the sub-folders in tact e.g. dir1/
img1.jpg, dir2/img1.jgp, dir1/dir3/img1.jpg etc....

Yes indeedy.

From: "Casimir P said:
Well technically that does NOT find subdirectories. Call in the
disqualifier dogs!!!!!!

WTFOMGLOLN00B!1!!

:)
 
L

Lloyd Linklater

Tim said:
files = Dir.glob("img/**/*.jpg")

pretty sure that keeps all the sub-folders in tact e.g. dir1/
img1.jpg, dir2/img1.jgp, dir1/dir3/img1.jpg etc....

I verified that this returns a fully qualified path. Ruby wins again!
 
R

Robert Klemme

files = Dir["img/**/*.jpg"]
Well technically that does NOT find subdirectories. Call in the
disqualifier dogs!!!!!!
Allow me to draw your attention to the **

It sweeps subfolders.
But supposedly you cant tell whats what now. Its all just a big blur. You
get all the little images but lose the bigger picture.

Its what happens when you dont keep track of the subdirectories.

Frankly, it's quite unclear to me what you want. When I run your script
I see *all* directories printed plus image file names without a path.
If that is what you want, then you can do this in "one" line:

$ ruby -r find -e 'Find.find(".") {|f| if File.directory? f then puts f
elsif /\.(jpg|png)$/i =~ f then puts File.basen
ame(f) end }'

Or, printed a bit more verbose and added handling of multiple base
directories:

require 'find'

ARGV.each do |dir|
Find.find dir do |f|
if File.directory? f
puts f
elsif /\.(?:jpg|png)$/i =~ f
puts File.basename(f)
end
end
end

Still very concise and readable. The complicatedness of the original
code cannot be attributed to Ruby.

Cheers

robert
 
W

Wayne Magor

Tim said:
files = Dir.glob("img/**/*.jpg")

Why doesn't that seem to work for me on Windows? Is there something
different about it on Windows than on Linux?

ruby -e 'puts Dir.glob("*.txt")' # Works for all .txt files in cur
dir
ruby -e 'puts Dir.glob("/**/*.txt")' # Prints nothing
ruby -e 'puts Dir.glob("**/*.txt")' # Works if done from subdir, not
from C:\

Is there something different about being at the top-level directory on
Windows? It's unexpected behavior for me. Why does it operate like
that?
 
C

Chad Perrin

Why doesn't that seem to work for me on Windows? Is there something
different about it on Windows than on Linux?

ruby -e 'puts Dir.glob("*.txt")' # Works for all .txt files in cur
dir
ruby -e 'puts Dir.glob("/**/*.txt")' # Prints nothing
ruby -e 'puts Dir.glob("**/*.txt")' # Works if done from subdir, not
from C:\

Is there something different about being at the top-level directory on
Windows? It's unexpected behavior for me. Why does it operate like
that?

I don't currently have an MS Windows machine with Ruby installed here, so
I can't check this -- but does it perhaps have something to do with
Microsoft's odd ideas about directory path separators? Perhaps it would
work like this on MS Windows and/or DOS:

files = Dir.glob("img\\**\\*.jpg")

Someone correct me if I'm wrong.
 
C

Casimir P

From: "Casimir P said:
All this just to find subdirectories and to list all the jpg files
inside!!
files = Dir["img/**/*.jpg"]

Its too late for me!! EaArgv[0]!! Spaghetti! I am fallliiiiiiiiiing!!
"Procedural or death - RIP"

Only dozens of micro galleries remained after... What do you think? It
took me 17 hours to make. Or was it minutes? hehe 8)

#microgallery.rb
#command syntax: "ruby mgall.rb [directorypath]"
#Renders a html gallery from images inside the path passed as argument
#saves "mgallery.html" to current dir
def IndexImagesInDirs(pathstr)
#returns a hash with key equal to subdirectory name and
#value is an array with names of all images inside
#works only on dir path in pathstr, not recursive
require 'find'
photodirs = Hash.new
photodirs[pathstr]=IndexImages(pathstr) #index images in root
Find.find(pathstr) do |item|
if FileTest.directory?(item)
if item != pathstr #not same dir, tho
tmp = IndexImages(item)
if (tmp.length > 0) #non-empty
photodirs[item]=tmp
end
end
end
end
return photodirs
end

def IndexImages(pathstr)
#Returns an array with filenames in pathstr
#that have extension equal to defined imageformats
imageformats = ["jpg", "png", "svg", "gif", "bmp"]
tmparr = Array.new
pathstr.each { |d|
Dir.entries(d).each { |filu|
nn = filu.to_s
ext = nn.downcase.split(".").last
imageformats.each { |frm|
if (ext == frm)
tmparr << filu
end
}
}
}
return tmparr
end

def ImageList(pathstr)
#point this to the directory with images in subdirectory-galleries
#makes a one page html list gallery from the images
#images in root are added as

dirs = IndexImagesInDirs(pathstr)

htmlpagestr = "<html><head></head><body>"
dirs.each { |key, value|
value.each { |val|
val.insert(0, "/")
htmlpagestr += '<p><img src="'
htmlpagestr += key.to_s + val.to_s
htmlpagestr += '" /><br/>image path: '
htmlpagestr += key.to_s +
val.to_s
htmlpagestr += '<br/><br/></p><hr/>'
}
}
return htmlpagestr = htmlpagestr + "</body></html>\n"
end


#start measuring time
time1 = Time.new.to_f
#make gallery
html = ImageList(ARGV[0])

#save to file
aFile = File.new("mgallery.html", "w")
aFile << html
aFile.close

#stop measuring time
time1 = Time.new.to_f - time1
time1 *= 10
puts "total time required in time integer unit seconds " + time1.to_i.to_s

#end microgallery
 
M

Marc Heiler

"You get all the little images but lose the bigger picture."

What "bigger picture" exactly? You just want to find the image files, or
not?

The one liner seems nice.
 
P

Phrogz

Why doesn't that seem to work for me on Windows? Is there something
different about it on Windows than on Linux?

Is there something different about being at the top-level directory on
Windows? It's unexpected behavior for me. Why does it operate like
that?

Looks like it behaves oddly at the root:
C:\>irb
irb(main):001:0> Dir.glob( './**/*.rb' ).length
=> 2
irb(main):002:0> Dir.chdir( 'c:/documents and settings/gavin.kistner/
desktop' )
=> 0
irb(main):003:0> Dir.glob( './**/*.rb' ).length
=> 638
irb(main):004:0> Dir.chdir( 'c:/' )
=> 0
irb(main):005:0> Dir.glob( './**/*.rb' ).length
=> 2
irb(main):006:0> Dir.glob( '.\\**\\*.rb' ).length
=> 0

Further evidence, showing that it's not an issue with ** not diving
more than a couple levels deep:


C:\tmp>irb
irb(main):001:0> Dir.glob( './**/*.rb' )
=> ["./l1/l1.rb", "./l1/l2/l2.rb", "./l1/l2/l3/l3.rb", "./l1/l2/l3/l4/
l4.rb"]
irb(main):002:0> Dir.chdir( '..' )
=> 0
irb(main):003:0> Dir.glob( './**/*.rb' )
=> ["./const_alias1.rb", "./const_alias2.rb"]
irb(main):004:0> Dir.glob( 'tmp/**/*.rb' )
=> ["tmp/l1/l1.rb", "tmp/l1/l2/l2.rb", "tmp/l1/l2/l3/l3.rb", "tmp/l1/
l2/l3/l4/l4.rb"]

Smells like a bug to me, but that's a dangerous claim for someone who
hasn't looked at the implementation. Certainly unexpected behavior by
me, too.
 
C

Casimir P

I am sorry! Can I make up for my evil ways? I try the ruby way!
I admint! ITs simple. 20 mins, half the lines.
Csmr
;)

#Microgallery V0.2
#command syntax: "ruby mgall.rb argdirectory"
#Renders a html gallery from images in path passed as argument 0 and 1
levels down
time1 = Time.new #start the clock!
imageformats = ["jpg", "png", "svg", "gif", "bmp"]
subdirs = Array.new
imageformats.each { |frm|
spath = ARGV[0] + "/*/*." + frm
subdirs.concat(Dir[spath]) #all imgpaths 2 arr
}
#insert img paths into html code
htmlpagestr = "<html><head></head><body>\n"
subdirs.each { |val|
htmlpagestr += '<p><img src="' + val.to_s
htmlpagestr += '" /><br/>image path: ' + val.to_s
htmlpagestr += "<br/><br/></p><hr/>\n"
}
htmlpagestr = htmlpagestr + "</body></html>"
#save to file
aFile = File.new("mgallery.html", "w")
aFile << htmlpagestr
aFile.close
puts "total time (ZYs): " + ((Time.new - time1)*100000).to_i.to_s
 
R

Rob Biedenharn

(Dang signed emails not going through!)

files = Dir["img/**/*.jpg"]

Well technically that does NOT find subdirectories. Call in the
disqualifier dogs!!!!!!

Allow me to draw your attention to the **

It sweeps subfolders.
But supposedly you cant tell whats what now. Its all just a big
blur. You
get all the little images but lose the bigger picture.

Its what happens when you dont keep track of the subdirectories.

Csrm

puts Dir["img/**/*.{png,jpg}"]

I really don't understand what you mean about keeping track of the
subdirectories. If you just want to know which directories hold
images (your code noted both jpg and png), then do this:

puts Dir["img/**/*.{png,jpg}"].map{|f| File.dirname(f)}.uniq

Or get the count of images in each directory:

Dir["img/**/*.{png,jpg}"].inject(Hash.new {|h,k|h[k] = 0}) { |h,f|
h[File.dirname(f)] += 1; h
}.each do |d,c|
puts "%5d images in %s"%[c,d]
end

OK, so that's not exactly "simple", but it is still going to be
better than the dozens of lines of code you originally posted. (and
with a bit of a comment to document the intent, quite easy to follow)

I agree with Robert on the original complexity not being a function
of using Ruby as the language.

-Rob

Rob Biedenharn http://agileconsultingllc.com
(e-mail address removed)
 

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

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,068
Latest member
MakersCBDIngredients

Latest Threads

Top