Filed under: Uncategorized
I’m working on a site that has a fixed page height and should not scroll. Because of this, the amount of text displayed on a page needs to not exceed a maximum value. I wrote the following function to break a string into lines based on either line breaks, or the amount of characters that can fit across the div.
Ruby 1.9 already has a function to break a string into lines; however, this does not include the option to break up a line based on characters and I am still on Ruby 1.8.6.
def lines s, chars=0
string = s
line_array = Array.new
while(string.size > 0)
i = string.index("\n")
# Takes the string up to either the first line break
line = string.slice!(0..(i || string.size - 1)).chomp
# Breaks the line up into separate lines based on the number of characters
if line.size > chars && chars > 0
while(line.size > chars)
ending = chars - 1
unless line[ending + 1, 1] == " "
ending = line.size - 1 - line.reverse.index(" ", -ending)
end
line_array << line.slice!(0..ending).strip
end
end
line_array << line.strip
end
return line_array
end
Filed under: Uncategorized
I have started a project at work to monitor log files and send any errors to the engineers. I played around with it in Ruby and in no time had the code below, which worked wonderfully. Unfortunately, due to the way this particular project is deployed, ruby was not an option. Feel free to use this if you need to monitor files for changes.
require 'ftools'
log_file = "test.log"
last_change = File.mtime(log_file)
while(true)
if File.readable?(log_file) && (file_time = File.mtime(log_file)) > last_change
last_change = file_time
puts "Log has been updated"
end
end