0

Trying to do like Replace content in a file between two markers but the accepted answer doesn't seem to be working:

index.html

<!--start-->Hello world<!--end-->

myscript.rb

def replace(file_path, contents)
    file = File.open(file_path, "r+")
    html = ""

    while(!file.eof?)
        html += file.readline
    end

    file.close()

    return html.gsub(/<!--start-->(.*)<!--end-->/im, contents)
end

thing = ["Foo", "Bar", "Baz"].sample

replace("/path/to/index.html", thing)

After running ruby myscript.rb, index.html remains the same. I'm on Ruby 2.2.0.

Flynt Hamlock
  • 349
  • 2
  • 12

1 Answers1

2

Try changing you script as follows:

def replace(file_path, contents)
  content = File.read(file_path)
  new_content = content.gsub(/(<!--start-->)(.*)(<!--end-->)/im, "\\1#{contents}\\3")

  File.open(file_path, "w+") { |file| file.puts new_content }
  new_content
end

thing = ["Foo", "Bar", "Baz"].sample

replace("./my_file", thing)

For working with files - check this great tutorial!

Good luck!

Paweł Dawczak
  • 9,519
  • 2
  • 24
  • 37