Class | HTAuth::File |
In: |
lib/htauth/file.rb
|
Parent: | Object |
ALTER | = | "alter" |
CREATE | = | "create" |
STDOUT_FLAG | = | "-" |
file | [R] | |
filename | [R] |
Create or Alter a password file.
Altering a non-existent file is an error. Creating an existing file results in a truncation and overwrite of the existing file.
# File lib/htauth/file.rb, line 34 34: def initialize(filename, mode = ALTER) 35: @filename = filename 36: @mode = mode 37: @dirty = false 38: 39: raise FileAccessError, "Invalid mode #{mode}" unless [ ALTER, CREATE ].include?(mode) 40: 41: if (filename != STDOUT_FLAG) and (mode == ALTER) and (not ::File.exist?(filename)) then 42: raise FileAccessError, "Could not open passwd file #{filename} for reading." 43: end 44: 45: begin 46: @entries = {} 47: @lines = [] 48: load_entries if (@mode == ALTER) and (filename != STDOUT_FLAG) 49: rescue => e 50: raise FileAccessError, e.message 51: end 52: end
open a file yielding the the file object for use. The file is saved when the block exists, if the file has had alterations made.
# File lib/htauth/file.rb, line 17 17: def open(filename, mode = ALTER) 18: f = self.new(filename, mode) 19: if block_given? 20: begin 21: yield f 22: ensure 23: f.save! if f and f.dirty? 24: end 25: end 26: return f 27: end
return whether or not an alteration to the file has happened
# File lib/htauth/file.rb, line 55 55: def dirty? 56: @dirty 57: end
load up entries, keep items in the same order and do not trim out any items in the file, like commented out lines or empty space
# File lib/htauth/file.rb, line 92 92: def load_entries 93: @lines = IO.readlines(@filename) 94: @lines.each_with_index do |line,idx| 95: if entry_klass.is_entry?(line) then 96: entry = entry_klass.from_line(line) 97: v = { 'entry' => entry, 'line_index' => idx } 98: @entries[entry.key] = v 99: end 100: end 101: end
update the original file with the new contents
# File lib/htauth/file.rb, line 65 65: def save! 66: begin 67: case filename 68: when STDOUT_FLAG 69: $stdout.write(contents) 70: else 71: ::File.open(@filename,"w") do |f| 72: f.write(contents) 73: end 74: end 75: @dirty = false 76: rescue => e 77: raise FileAccessError, "Error saving file #{@filename} : #{e.message}" 78: end 79: end