Created
June 13, 2015 10:19
-
-
Save igrep/c62b3d0b3f39260d3687 to your computer and use it in GitHub Desktop.
#yokohamarb 「Rubyレシピブック」recipe 194「ファイルに1行挿入する」の修正 ref: http://qiita.com/igrep/items/6e123a3e6681b9a62352
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| require 'tempfile' | |
| require 'fileutils' | |
| def insert path, start_line, data | |
| pid = Process.pid.to_s | |
| Tempfile.create pid, File.dirname(path) do|temp| | |
| File.open(path) do|input| | |
| start_line.times do | |
| if line = input.gets | |
| temp.write line | |
| end | |
| end | |
| temp.puts data | |
| while line = input.gets | |
| temp.write line | |
| end | |
| end | |
| temp.flush | |
| mode = File.stat(path).mode | |
| # File.renameだとpathとtemp.pathのあるファイルシステムが違う場合、うまく行かない。 | |
| # どうせTempfile.createメソッドのブロックを出るときにtempは削除されるはずなので、cpする。 | |
| FileUtils.cp(temp.path, path) | |
| File.chmod(mode, path) | |
| end | |
| end | |
| insert ARGV[0], ARGV[1].to_i, ARGV[2] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment