app/models/effective/code_writer.rb in effective_developer-0.2.5 vs app/models/effective/code_writer.rb in effective_developer-0.2.6
- old
+ new
@@ -10,16 +10,17 @@
@newline = newline
@from = []
@to = []
+ @changed = false
+
@lines = File.open(filename).readlines
- block.call(self)
-
- File.open(filename, 'w') do |file|
- lines.each { |line| file.write(line) }
+ if block_given?
+ block.call(self)
+ write!
end
end
# Returns true if the insert happened, nil if no insert
def insert_after_last(content, depth: nil, content_depth: nil, &block)
@@ -88,11 +89,11 @@
if block?(contents) || !same?(contents, index)
lines.insert(index, newline)
end
end
- true
+ @changed = true
end
def insert_raw(content, index, depth = 0)
contents = (content.kind_of?(Array) ? content : content.split(newline))
@@ -105,10 +106,12 @@
lines.insert(index, (indent * depth) + content + newline)
end
index += 1
end
+
+ @changed = true
end
# Iterate over the lines with a depth, and passed the stripped line to the passed block
def each_with_depth(&block)
depth = 0
@@ -192,10 +195,28 @@
end
depth
end
+ def changed?
+ @changed == true
+ end
+
+ def gsub!(source, target)
+ lines.each { |line| @changed = true if line.gsub!(source, target) }
+ end
+
private
+
+ def write!
+ return false unless changed?
+
+ File.open(filename, 'w') do |file|
+ lines.each { |line| file.write(line) }
+ end
+
+ true
+ end
def open?(content)
stripped = ss(content)
[' do'].any? { |end_with| stripped.split('#').first.to_s.end_with?(end_with) } ||