I have some Ruby code that processes a Gemfile. It adds some recommended gems and removes other gems. There's a section of a Gemfile that looks like the following:
group :development, :test do
# The gem version is a recommended starting place; upgrade if needed.
gem 'pry-rails', '~> 0.3.4'
# Enhance pry with byebug (which gives more debugger commands and other goodies).
# The gem version is a recommended starting place; upgrade if needed.
gem 'pry-byebug', '~> 3.4.0'
# Use rspec for testing
gem 'rspec-rails', '~> 3.5.1'
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug', platform: mri
end
I'm using the following two lines to remove the last two lines of the block (the gem 'byebug ...
line and the comment above it).
gsub_file(full_app_gemfile_path, /^\s*gem\s*("|')byebug.*$/, "", verbose: false)
gsub_file(full_app_gemfile_path, /^\s*#.*Call.*("|')byebug("|').*$/, "", verbose: false)
The gsub_file
is a method provided by the Thor
gem. The removal works, but I end up with the following code in the Gemfile
group :development, :test do
# The gem version is a recommended starting place; upgrade if needed.
gem 'pry-rails', '~> 0.3.4'
# Enhance pry with byebug (which gives more debugger commands and other goodies).
# The gem version is a recommended starting place; upgrade if needed.
gem 'pry-byebug', '~> 3.4.0'
# Use rspec for testing
gem 'rspec-rails', '~> 3.5.1'
end
Why is that extra blank line being inserted after group :development, :test do
? It's nowhere near where the lines were removed. It could possibly be a bug in the Thor gem, but I'm wondering if it's regex issue.
Update
I just tried using the raw ruby gsub (to eliminate potential Thor issues). I created a helper method
def my_gsub(path, regex, str)
text = File.read(path)
rep = text.gsub(regex, str)
File.open(path, "w") {|file| file.puts rep}
end
When I change the two lines that are calling gsub_file
to call my_gsub
, I now get two blank lines after group :development, :test do
.
For your method my_gsub
you are replacing the content of the line without replacing the linebreak. To make it remove the newline as well you can change your regex to this:
gsub_file(full_app_gemfile_path, /^\s*gem\s*("|')byebug.*$\n/, "")
gsub_file(full_app_gemfile_path, /^\s*#.*Call.*("|')byebug("|').*$\n/, "")