I'm writing a small ruby daemon that I am hoping will do the following:
- Check if a specific directory has files (in this case, .yml files)
- If so, take the first file (numerically sorted preferrably), and parse into a hash
- Do a 'yield', with this hash as the argument
What I have right now is like:
loop do
get_next_in_queue { |s| THINGS }
end
def get_next_in_queue
queue_dir = Dir[File.dirname(__FILE__)+'/../queue']
info = YAML::load_file(queue_dir[0]) #not sure if this w开发者_JAVA技巧orks or not
yield info
end
I'd like to make the yield conditional if possible, so it only happens if a file is actually found. Thanks!
Okay, I got this working!
The problem with queue_dir.empty?
is that a directory always contains [".", ".."]
So what I did was:
def get_next_in_queue
queue_dir = Dir.entries(File.dirname(__FILE__)+'/../queue')
queue_dir.delete "."
queue_dir.delete ".."
if !queue_dir.empty?
info = YAML::load_file("#{File.dirname(__FILE__)}/../queue/#{queue_dir[0]}")
yield stem_info
else
sleep(30) #since it is empty, we probably don't need to check instantly
end
end
Just add additional checks:
def get_next_in_queue
queue_dir = Dir[File.dirname(__FILE__)+'/../queue']
return if queue_dir.empty?
info = YAML::load_file(queue_dir[0]) #not sure if this works or not
yield info if info
end
Depending on your wanted behaviour, you can additionally raise an exception, log an error, sleep for N seconds etc.
精彩评论