Class: Polygon::Script::Gsub
- Inherits:
-
Object
- Object
- Polygon::Script::Gsub
- Defined in:
- lib/polygon/script/gsub.rb
Instance Attribute Summary collapse
-
#dry_run ⇒ Object
Returns the value of attribute dry_run.
-
#folder ⇒ Object
Returns the value of attribute folder.
-
#pattern ⇒ Object
Returns the value of attribute pattern.
-
#regexp ⇒ Object
Returns the value of attribute regexp.
Instance Method Summary collapse
-
#binary?(file) ⇒ Boolean
Stolen from ptools (github.com/djberg96/ptools).
- #execute(args) ⇒ Object
- #gsub(file, from, to) ⇒ Object
Instance Attribute Details
#dry_run ⇒ Object
Returns the value of attribute dry_run.
5 6 7 |
# File 'lib/polygon/script/gsub.rb', line 5 def dry_run @dry_run end |
#folder ⇒ Object
Returns the value of attribute folder.
5 6 7 |
# File 'lib/polygon/script/gsub.rb', line 5 def folder @folder end |
#pattern ⇒ Object
Returns the value of attribute pattern.
5 6 7 |
# File 'lib/polygon/script/gsub.rb', line 5 def pattern @pattern end |
#regexp ⇒ Object
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)
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 .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.}" end |