Class: Mopup
- Inherits:
-
Object
- Object
- Mopup
- Defined in:
- lib/mopup.rb
Overview
Mops up trailing white space and optionally converts leading tabs to spaces
Constant Summary collapse
- VERSION =
'0.0.2'
Instance Attribute Summary collapse
-
#options ⇒ Object
readonly
The clean-up options.
Instance Method Summary collapse
-
#clean(line) ⇒ Object
Cleans the whitespace in a line of text.
-
#clean_dir(path, recurse = false, &block) ⇒ Object
Cleans each plain text file within the directory located at
path
. -
#clean_file(path) ⇒ Object
Cleans each line in file located at
path
. -
#clean_text(text) ⇒ Object
Returns a copy of text with the whitespace in each line cleaned up.
-
#initialize(options = nil) ⇒ Mopup
constructor
Examples.
Constructor Details
#initialize(options = nil) ⇒ Mopup
Examples
# To translate tabs to 2 spaces
Mopup.new :translate_tabs_to_spaces => true, :tab_stop => 2
26 27 28 29 30 31 32 |
# File 'lib/mopup.rb', line 26 def initialize( = nil) @options = { :translate_tabs_to_spaces => false, :tab_stop => 2 } @options.merge!() if end |
Instance Attribute Details
#options ⇒ Object (readonly)
The clean-up options
-
:translate_tabs_to_spaces
Translate leading tabs to spaces -
:tab_stop
Number of spaces to which tabs should be translated
18 19 20 |
# File 'lib/mopup.rb', line 18 def @options end |
Instance Method Details
#clean(line) ⇒ Object
42 43 44 45 46 47 48 |
# File 'lib/mopup.rb', line 42 def clean(line) if @options[:translate_tabs_to_spaces] line.gsub!(/\t/, ' ' * @options[:tab_stop]) end line.rstrip! line end |
#clean_dir(path, recurse = false, &block) ⇒ Object
Cleans each plain text file within the directory located at path
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 |
# File 'lib/mopup.rb', line 82 def clean_dir(path, recurse = false, &block) Dir.foreach(path) do |entry| unless entry =~ /^\./ full_path = path.chomp('/') + '/' + entry if File.file? full_path result = 'skipped' unless File.binary? full_path clean_file(full_path) result = 'cleaned' end block.call(full_path, result) if block elsif File.directory? full_path and recurse clean_dir(full_path, recurse, &block) end end end end |
#clean_file(path) ⇒ Object
Cleans each line in file located at path
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
# File 'lib/mopup.rb', line 62 def clean_file(path) tmp = Tempfile.new('mopup') stat = File.stat(path) begin File.open(path) do |f| while line = f.gets clean(line) tmp.puts line end end tmp.close FileUtils.mv(tmp.path, path) File.chmod(stat.mode, path) File.chown(stat.uid, stat.gid, path) ensure tmp.close! end end |
#clean_text(text) ⇒ Object
Returns a copy of text with the whitespace in each line cleaned up
51 52 53 54 55 56 57 58 59 |
# File 'lib/mopup.rb', line 51 def clean_text(text) buffer = '' text.lines do |line| clean(line) yield(line) if block_given? buffer << line end buffer end |