module Completable
Completable
file-objects can treat their contents like a fillable form. Predefined fields are searched and replaced by values.
Attributes
backup[R]
summary[R]
Public Instance Methods
complete(subst_def, &b)
click to toggle source
The main function of this module. Expects as parameters a Hash of field/substitution- pairs and an optional block. If a block is given, the original file will be processed and a backup is created.
# File lib/completable.rb, line 36 def complete(subst_def, &b) @summary = Summary.new(subst_def) @field_count = 0 if(self.respond_to?(:gets) ) if(self.respond_to?(:closed?) && !self.closed?) self.rewind if(subst_def && subst_def.respond_to?(:has_key?)) cpos = 0 if(!b) @backup="#{self.path}_backup" outfile = File.open(@backup, 'w'){|bf| bf.write(self.readlines() )} self.rewind end while(chunk = self.gets()) chunk, msg = process(chunk, subst_def) if(!chunk && msg) return nil, msg end if(b) b.call(chunk) else self.seek(cpos, IO::SEEK_SET) self.write(chunk) end cpos = self.pos end else return nil, 'first parameter must be a Hash' end else return nil, 'completable object must at least be open for reading' end else return nil, 'completable object must also respond to :gets' end @field_count end
field_delimiter()
click to toggle source
returns the character sequence, which marks substitutable text
# File lib/completable.rb, line 82 def field_delimiter() if(!@field_delimiter) field_delimiter=(' ') end @field_delimiter end
field_delimiter=(d)
click to toggle source
sets the character sequence, which marks substitutable text
# File lib/completable.rb, line 76 def field_delimiter=(d) @field_delimiter = d @field_regex = Regexp.new("#{d}[^#{d}]*#{d.reverse}") end
Private Instance Methods
process(chunk, subst_def)
click to toggle source
processes one chunk of text with the given map of field/substitution pairs
# File lib/completable.rb, line 93 def process(chunk, subst_def) if(@field_regex) # rpl = chunk.match(@field_regex) fields = chunk.scan(@field_regex) fields.each do |rpl| if rpl # offset = rpl.offset(0) if rpl offset = chunk.index(rpl) test_key = rpl.to_s.delete(@field_delimiter) test_key = test_key.to_sym if test_key if(subst_def.has_key?(test_key)) @summary.add_found(test_key) value = subst_def[test_key] chunk.gsub!(rpl.to_s, value) if value @field_count += 1 end end end chunk else return nil, 'field-delimiter must be set.' end end