Class: Polygon::Script::Gsub

Inherits:
Object
  • Object
show all
Defined in:
lib/polygon/script/gsub.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#dry_runObject

Returns the value of attribute dry_run.



5
6
7
# File 'lib/polygon/script/gsub.rb', line 5

def dry_run
  @dry_run
end

#folderObject

Returns the value of attribute folder.



5
6
7
# File 'lib/polygon/script/gsub.rb', line 5

def folder
  @folder
end

#patternObject

Returns the value of attribute pattern.



5
6
7
# File 'lib/polygon/script/gsub.rb', line 5

def pattern
  @pattern
end

#regexpObject

Returns the value of attribute regexp.



5
6
7
# File 'lib/polygon/script/gsub.rb', line 5

def regexp
  @regexp
end

Instance Method Details

#binary?(file) ⇒ Boolean

Stolen from ptools (github.com/djberg96/ptools)

Returns:

  • (Boolean)


28
29
30
31
# File 'lib/polygon/script/gsub.rb', line 28

def binary?(file)
  s = (File.read(file, File.stat(file).blksize) || "").split(//)
  ((s.size - s.grep(" ".."~").size) / s.size.to_f) > 0.30
end

#execute(args) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
# File 'lib/polygon/script/gsub.rb', line 45

def execute(args)
  abort options.to_s unless args.size >= 2
  from     = args.shift
  from     = Regexp.compile(regexp ? from : Regexp.escape(from))
  to       = args.shift
  files    = args.empty? ? folder.glob(pattern) : args.map(&Path)
  files.each do |file|
    next if file.directory? or binary?(file)
    gsub(file, from, to)
  end
end

#gsub(file, from, to) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
# File 'lib/polygon/script/gsub.rb', line 33

def gsub(file, from, to)
  gsubbed = file.read.gsub!(from){|m| 
    msg = "gsub #{m[0, (50 - to.length)]} -> #{to}"
    msg += " "*(60 - msg.length) + " (#{file})" 
    info msg 
    to
  }
  file.write(gsubbed) if gsubbed && !dry_run
rescue ArgumentError => ex
  error "Skipping #{file}: #{ex.message}"
end