module StringInFile
Constants
- VERSION
Public Class Methods
add_beginning(str_to_add, path)
click to toggle source
# File lib/string_in_file.rb, line 55 def self.add_beginning(str_to_add, path) path_old = "#{path}.old" system("mv #{path} #{path_old}") # Create a new file and write to it file_to_write = File.open(path, 'w') file_to_write.puts str_to_add File.foreach(path_old) do |line| file_to_write.puts line end file_to_write.close # Delete the old file system("rm -f #{path_old}") end
add_end(str_to_add, path)
click to toggle source
# File lib/string_in_file.rb, line 71 def self.add_end(str_to_add, path) path_old = "#{path}.old" system("mv #{path} #{path_old}") # Create a new file and write to it file_to_write = File.open(path, 'w') File.foreach(path_old) do |line| file_to_write.puts line end file_to_write.puts str_to_add file_to_write.close # Delete the old file system("rm -f #{path_old}") end
present(str_to_find, path)
click to toggle source
# File lib/string_in_file.rb, line 42 def self.present(str_to_find, path) begin # loop through each line in the file File.foreach(path) do |line| # does the line contain our string? return true if line.include?(str_to_find) end return false rescue return false end end
read(path)
click to toggle source
Put contents of file into string Thanks to Keith R. Bennett for suggesting this solution on ruby.mn. Please note that newlines are removed. Thus, this is designed to work with 1-line strings.
# File lib/string_in_file.rb, line 9 def self.read(path) str_output = File.readlines(path).join('') str_output = str_output.delete("\n") end
replace(string1, string2, path)
click to toggle source
Replace all instances of string1 in a file with string2 If string1 does not exist in the file, or if the file does not exist, no action is taken.
# File lib/string_in_file.rb, line 22 def self.replace(string1, string2, path) path_old = "#{path}.old" system("mv #{path} #{path_old}") # Create a new file and write to it file_to_write = File.open(path, 'w') File.foreach(path_old) do |line| # does the line contain our string? if line.include?(string1) file_to_write.puts line.gsub!(string1, string2) else file_to_write.puts line end end file_to_write.close # Delete the old file system("rm -f #{path_old}") end
write(str_to_write, path)
click to toggle source
Writes the value of a string into a file
# File lib/string_in_file.rb, line 15 def self.write(str_to_write, path) File.open(path, 'w') { |f| f.write(str_to_write) } end