Sha256: 5272888c7036a10105e950fca4769421b520763084b0251d543ca916dc074b16

Contents?: true

Size: 1.16 KB

Versions: 4

Compression:

Stored size: 1.16 KB

Contents

module Stairs
  module Util
    module FileMutation
      class << self
        def replace_or_append(pattern, string, filename)
          if File.exists? filename
            contents = File.read filename
            if contents =~ pattern
              contents.sub! pattern, string
              write contents, filename
              return
            end
          end

          write_line string, filename
        end

        def remove(pattern, filename)
          return unless File.exists? filename

          contents = File.read filename
          if contents =~ pattern
            contents.slice!(pattern)
            write contents, filename
          end
        end

        def write_line(string, filename)
          File.open filename, "a+" do |file|
            # ensure file ends with newline before appending
            last_line = file.each_line.reduce("") { |m, l| l }
            file.puts "" unless last_line == "" || last_line =~ /(.*)\n/

            file.puts string
          end
        end

        def write(string, filename)
          File.open filename, "w+" do |file|
            file.puts string
          end
        end
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
stairs-0.9.0 lib/stairs/util/file_mutation.rb
stairs-0.8.0 lib/stairs/util/file_mutation.rb
stairs-0.7.1 lib/stairs/util/file_mutation.rb
stairs-0.7.0 lib/stairs/util/file_mutation.rb