Class: Kasoba

Inherits:
Object
  • Object
show all
Defined in:
lib/kasoba.rb,
lib/kasoba/version.rb

Constant Summary collapse

VERSION =
"0.0.3"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options, regex, replacement) ⇒ Kasoba

Returns a new instance of Kasoba.



16
17
18
19
20
21
22
# File 'lib/kasoba.rb', line 16

def initialize(options, regex, replacement)
  @files = FileNavigator.new(options[:dir],options[:extensions])
  @count = options[:count]
  @editor = options[:editor]
  @regex = regex
  @replacement = replacement
end

Instance Attribute Details

#filesObject (readonly)

Returns the value of attribute files.



6
7
8
# File 'lib/kasoba.rb', line 6

def files
  @files
end

Instance Method Details

#countObject



33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/kasoba.rb', line 33

def count
  num = 0
  @files.each do |file|
    file.each do |line|
      cline = line.clone
      while ((t = cline.partition(@regex)[2]) != "") or (cline.match(@regex)) do
        cline = t
        num = num +1
      end
    end
    file.close
  end
  return num
end

#replaceObject



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/kasoba.rb', line 48

def replace
  @files.each do |file|
    File.open(file.path + ".temp","w") do |tmpFile|
      p file.path
      fileContent = file.readlines.join
      while (((t = fileContent.partition(Regexp.new(@regex)))[2] != "") or t.join.length > 0)
        if(t[2] != "")
          tmpFile << t[0]
          fileContent = t[2]
          oldline = t[0].split("\n").last.to_s + t[1]
          puts "Oldline: " + oldline.color(:red)
          localreplacement = @replacement.nil?? ask('Type substitution string') : @replacement
          i = 1
          t[1].match(@regex).captures.each do |capture|
            localreplacement = localreplacement.gsub("\\#{i}" ,capture )
            i = i + 1
          end
          newline = t[0].split("\n").last.to_s + localreplacement + t[2].split("\n").first.to_s
          puts "Newline: " + newline.color(:green)
          if agree("Agree? y/n".color(:blue))
            tmpFile << localreplacement
          else
            tmpFile << t[1]
          end
        else
          fileContent = t[2]
          tmpFile << t.join
        end
      end
    end
    filePath = file.path
    file.close
    File.delete(filePath)
    File.rename(filePath + ".temp", filePath)
  end
end

#runObject



7
8
9
10
11
12
13
14
# File 'lib/kasoba.rb', line 7

def run
  if @count == true
    say("Counting ...")
    p count
  else
    replace
  end
end